











YSPerson *person = [[YSPerson alloc]init];
YSCat *cat = [[YSCat alloc]init];
person.cat = cat;
[person setValue:@10 forKey:@"age"];
[person setValue:@60 forKeyPath:@"cat.weight"];
NSLog(@"%@",[person valueForKey:@"age"]);
NSLog(@"%@",[person valueForKeyPath:@"cat.weight"]);



1、iOS 用什么方式实现对一个对象的KVO?(KVO的本质是什么?)
1、利用RuntimeAPI动态生成一个子类(命名eg:NSKVONotifying_MJPerson),并且让instance对象的isa指针指向这个全新的子类;
2、当修改instance对象的属性时,会调用Foundation的_NSSetXXXValueAndNotify函数:
(1)willChangeValueForKey:
(2)父类原来的setter
(3)didChangeValueForKey:(内部会触发监听器(Oberser)的监听方法(observeValueForKeyPath:ofObject:change:context:))
2、如何手动触发KVO?
手动调用willChangeValueForKey:和didChangeValueForKey:
3、直接修改成员变量会触发KVO么?
不会触发KVO
4、KVC的赋值和取值过程是怎样的?原理是什么?
如setValue:forKey:原理图所示;
如valueForKey:原理图所示;
5、通过KVC修改属性会触发KVO么?
会触发KVO
原因:
[person setValue:@10 forKey:@“age”];
系统内部实现等同于
[person willChangeValueForKey:@“age”];
person -> _age = 10;
[person didChangeValueForKey:@“age”];
网友评论