KVC KVO
KVC 赋值方式 key value coding 键值编码
KVO key value observer 键值监听
[item setValue:@"西门吹雪" forKey:@"name"];
1、item里找叫做name的属性去赋值
2、如果没找到,找叫做_name的成员变量
3、还没找到,找叫做name的成员变量
4、还没找到,就调item里的valueForUndefinedKey:方法
item = [[UserItem alloc] init];
// item.name = @"西门吹雪";
// NSLog(@"%@",item.name);
//第1种赋值方式
[item setValue:@"西门吹雪" forKey:@"name"];
NSLog(@"%@",[item valueForKey:@"name"]);
item.wugong = [[WuGongItem alloc] init];
//第2种赋值方式
[item setValue:@"独孤九剑" forKeyPath:@"wugong.wuGongName"];
NSLog(@"%@",[item valueForKeyPath:@"wugong.wuGongName"]);
//第3种赋值方式
[item setValuesForKeysWithDictionary:(NSDictionary *)];
//KVO self监听item中的name (谁调用方法,我们监听谁)
[item addObserver:self forKeyPath:@"name" options:NSKeyValueObservingOptionNew context:NULL];
item.name = @"叶孤城";
}
//KVO监听的值发生变化调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"%@",change[@"new"]);
}