- (void)viewDidLoad {
[super viewDidLoad];
self.person = [[Person alloc]init];
self.person.age = 15;
* 注册监听
*/
[self.person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
* 第二次赋值 20
*/
self.person.age = 20;
* 再次赋值 20
*/
self.person.age = 20;
* 详细见控制台输出,只比较新旧值
*/
}
* 监听回调
*/
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"n change = %@ n keyPath =%@ object =%@ context=%@",change ,keyPath,object,context);
*
change = {
kind = 1;
new = 20; --------->新的值是 20 注册监听后,observeValueForKeyPath会回调输出
old = 15; --------->旧的值是 15 注册监听前,这个属性初始化时候就是15。
}
keyPath =age object =<Person: 0x7feec962a9d0> context=(null)
change = {
kind = 1;
new = 20; --------->新的值是 20 再次传入20,observeValueForKeyPath这个还是会回调输出
old = 20; --------->旧的值是 20
}
keyPath =age object =<Person: 0x7feec962a9d0> context=(null)
*/
* 由控制台输出结果得出结论,只要是对属性进行改变,不管属性的值是否变化,不区分新旧值的变化,observeValueForKeyPath都是回调,通知观察者的。
*/
}
-(void)dealloc{
* 移除观察
*/
[self.person removeObserver:self forKeyPath:@"age"];