KVC是一种非常方便的给各种自定义类的属性赋值的方式
@interface Person : NSObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *gender;
@end
@class Person;
@interface Earth : NSObject
@property (nonatomic, retain) Person *person;
@end
-(void)setValue:forKey://Key是实例变量的变量名
Person *p = [[Person alloc] init];
[p setValue:[NSString stringWithFormat:@"Archer"] forKey:@"name"];
Earth *earth = [[Earth alloc] init];
[earth setValue:p forKey:@"person"];
-(id)valueForKey:
NSString *st = [p valueForKey:@"name"];
-(id)valueForKeyPath://点语法表示路径
NSString *pN = [earth valueForKeyPath:@"person.name"];
-(void)setValue:forKeyPath:
[earth setValue:@"Smith" forKeyPath:@"person.name"];
-(void)setValuesForKeysDictionary://以字典里的key作key,以字典里的value做value,这是一种快捷写法
NSDictionary *pD = [[NSDictionary alloc] initWithObjectsAndKeys:@"Mary",@"name",@"W",@"gender",nil];
[p setValuesForKeysDictionary:pD];
-(void)setValue:forUndefinedKey://如果输入的key和变量名以及其变体(key,_key,isKey,_isKey)不同,就会崩溃,如果想要通过这样的key访问,就需要重写Undefined方法
-(id)valueForUndefinedKey:
@implementation Person
-(void)setValue:(id)value forUndefinedKey:(NSString*)key{
if ([key isEqualToString:@"name1"]) {
self.name = value;
}else if ([key isEqualToString:@"gender1"]) {
self.gender = value;
}
}
-(id)valueForUndefinedKey:(NSString*)key {
if ([key isEqualToString:@"name1") {
return _name;
}else if ([key isEqualToString:@"gender1"]) {
return _gender;
}
@end
实现机制
1.setName: kvc赋值首先在类中查找set+Key:名字的方法;如果类中不存在这样的方法,转2
2.在类中查找和(_key、_isKey、key、isKey)相同的实例变量;如果实例变量不存在,转3
3.进入Undefined方法,需要自行重写setValue:forUndefinedKey:和valueForUndefinedKey: