KVC:key-value-coding
是一种早期简介给类成员属性进行设置与取值的方式,无论是@publiuc @protected 还是@private都能够间接访问得到.相当于现在的getter和setter的使用方式,后台为了安全性和效率,IOS出现了@property进行属性访问.
下面是KVC的实例:
//
// Child.h
// KVCDemo
//
// Created by 5016 on 13-12-19.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Child : NSObject
@property(assign,nonatomic)NSInteger sleep;
@property(retain,nonatomic)NSString* name;
@property(assign,nonatomic)NSInteger age;
-(Child*)initWithName:(NSString*)name andAge:(NSInteger)age andSleep:(NSInteger)sleep;
@end
//
// Child.m
// KVCDemo
//
// Created by 5016 on 13-12-19.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import "Child.h"
@implementation Child
@synthesize name = _name,age = _age,sleep=_sleep;
/*使用KVC可以间接访问类私有成员*/
-(Child*)initWithName:(NSString*)name andAge:(NSInteger)age andSleep:(NSInteger)sleep
{
if (self = [super init]) {
//KVC写法
//1.将传递过来的参数当做值来使用,实例变量当做key使用
//2.KVC要求value必须是一个对象的参数,如果是一个基本数据类型,要转换成为对象
//3.使用KVC的方式对实例变量的赋值,可能会引起参数的引用计数加1,(分两种情况)
//如果传过来的参数是一个本身就不需要做内存管理的参数,那这个时候就不会引起引用计数加1,相当于assign
//如果传递过来的参数是在堆里面开辟的内存空间,那么经过KVC赋值之后就会引起该参数的引用计数加1,所以需要在dealloc方法里面释放一次,保持平衡
//3.使用KVC方式,没有retain,assign等关键字提示,使用的时候需要特别的注意
[self setValue:name forKey:@"name"];
[self setValue:[NSNumber numberWithInteger:age] forKey:@"age"];
[self setValue:[NSNumber numberWithInteger:sleep] forKey:@"sleep"];
}
return self;
}
-(void)dealloc
{
[_name release];
[super dealloc];
}
@end
//
// Nurse.h
// KVCDemo
//
// Created by 5016 on 13-12-19.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import <Foundation/Foundation.h>
@class Child;
@interface Nurse : NSObject
@property(retain,nonatomic)NSString* name;
@property(assign,nonatomic)NSInteger age;
@property(assign,nonatomic)Child* child;
-(Nurse *)initWithName:(NSString*) name andAge:(NSInteger) age andChild:(Child*)child;
@end
//
// Nurse.m
// KVCDemo
//
// Created by 5016 on 13-12-19.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import "Nurse.h"
@implementation Nurse
@synthesize child = _child,name = _name,age=_age;
-(Nurse *)initWithName:(NSString*) name andAge:(NSInteger) age andChild:(Child*)child
{
if (self = [super init]) {
[self setValue:name forKey:@"name"];
[self setValue:[NSNumber numberWithInteger:age] forKey:@"age"];
[self setValue:child forKey:@"child"];
}
return self;
}
-(void)dealloc
{
[_child release];
[_name release];
[super dealloc];
}
@end
//
// main.m
// KVCDemo
//
// Created by 5016 on 13-12-19.
// Copyright (c) 2013年 dradon. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Nurse.h"
#import "Child.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Child *child = [[Child alloc]initWithName:@"dragon" andAge:23 andSleep:59];
Nurse *nurse = [[Nurse alloc]initWithName:@"xinxi" andAge:22 andChild:child];
NSLog(@"child.name=%@",[child valueForKey:@"name"]);//使用KVC取值
NSString *childName = [nurse valueForKeyPath:@"child.name"];//路径访问
NSLog(@"name=%@",childName);
}
return 0;
}