KVO的本质

2020-10-17  本文已影响0人  寒江飄雪

KVO的定义

KVO 的全称是Key-Value Observing,俗称“键值监听”,可以用于监听某个对象属性值的改变.

图片.png

使用

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.people1 = [[HPPeople alloc] init];
    self.people2 = [[HPPeople alloc] init];
    NSKeyValueObservingOptions option =  NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
    [self.people1  addObserver:self forKeyPath:@"age" options:option context:nil];
}

-(void)dealloc
{
    [self.people1 removeObserver:self forKeyPath:@"age"];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //people1的类对象为HPPeople
    self.people1.age = 5;
    //people2的类对象为NSKVONotifying_HPPeople
    self.people2.age = 3;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    NSLog(@"监听到%@的属性值%@发生了变化  %@  -  %@",object,keyPath,change,context);
}

点击打印结果

监听到<HPPeople: 0x6000013992e0>的属性值age发生了变化  {
    kind = 1;
    new = 5;
    old = 0;
}  -  (null)

添加断点

图片.png
people1对象和people2对象的赋值操作,其他属性都一样,people1对象的age变化了会打印,而people2不会打印.然后我们打断点发现people1的类对象发生了变化,变成NSKVONotifying_HPPeople

我们尝试着打印people1对象和people2对象添加观察者前后的setAge:方法的实现
修改代码

-(void)viewDidLoad
{
    [super viewDidLoad];
    self.people1 = [[HPPeople alloc] init];
    self.people2 = [[HPPeople alloc] init];
    
    NSLog(@"people1未添加观察者之前 %p  %p",[self.people1 methodForSelector:@selector(setAge:)],[self.people2 methodForSelector:@selector(setAge:)]);
    NSKeyValueObservingOptions option =  NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
    [self.people1  addObserver:self forKeyPath:@"age" options:option context:nil];
    NSLog(@"people1添加观察者之后 %p  %p",[self.people1 methodForSelector:@selector(setAge:)],[self.people2 methodForSelector:@selector(setAge:)]);
}

打印结果

2020-10-16 20:22:17.118174+0800 gcd[67348:5498682] people1未添加观察者之前 0x1040c1d30  0x1040c1d30
2020-10-16 20:22:17.118736+0800 gcd[67348:5498682] people1添加观察者之后 0x1044478bc  0x1040c1d30
(lldb) p (IMP)0x1040c1d30
(IMP) $0 = 0x00000001040c1d30 (gcd`-[HPPeople setAge:] at HPPeople.h:15)
(lldb) p (IMP)0x1044478bc
(IMP) $1 = 0x00000001044478bc (Foundation`_NSSetLongLongValueAndNotify)
(lldb) 

那么添加了观察者对象people1的setAge:方法的实现变成Foundation框架的_NSSetLongLongValueAndNotify函数
我们通过反编译工具Hopper拿到Foundation框架的伪代码从中去查找_NSSetLongLongValueAndNotify函数看到的是汇编代码,大致的实现过程如下伪代码

 -(void)_NSSetLongLongValueAndNotify //伪代码
 {
    [self willChangeValueForKey:@"age"];
    //中间是原来setter的实现
    [self didChangeValueForKey:@"age"];
 }
  • 调用willChangeValueForKey:
  • 调用原来的setter实现
  • 调用didChangeValueForKey:didChangeValueForKey:内部会调用observer的observeValueForKeyPath:ofObject:change:context:方法

KVO的本质用图来展示如下


图片.png

结论:

KVO的本质是运用RuntimeApi动态的生成了一个子类,并让这个instance对象的isa指针指向这个全新的类,当修改这个instance对象的属性时就会调用全新子类的setter方法实现,这个setter方法的实现是调用了Fundation框架_NSSetXXXValueAndNotify的方法

上一篇下一篇

猜你喜欢

热点阅读