#import "ViewController.h"
#import "Person.h"
@interface ViewController ()
@property(nonatomic ,strong)Person * people;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person * people = [[Person alloc]init];
self.people = people;
people.name = @"xiaohua";
people.age = 10;
//KVO 键值监听 , 当监听某个类的某一个成员属性时,当这个成员属性的值发生改变时,做出响应
//key与keyPath 的区别: key 值找一层, 也就本类的的属性, 而keyPath 则可以向下寻找多层,也就是如果本类没有, 就向其子类中寻找, 如果都没有找到,就直接报错
[people addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld context:nil];
//KVO 的底层实现: 当程序运行到上一行代码时, 也就是给属性添加监听者时,此时动态生成一个NSKVONotifying_子类,并修改之前类的isa指针,将当前类的isa指针修改为动态生成的子类的isa指针,
然后当给类的属性赋值时, 就会调用子类的的set方法,根据监听者的参数,保存相应的数据,然后在set方法中调用父类的set方法,将值赋值给父类属性,然后调用observeValueForKeyPath 告诉监听者,属性的值发送改变了
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.people.age =10;
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
NSLog(@"%@" , change);
}