KVO

2020-04-13  本文已影响0人  大鹅ne

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


Screen Shot 2020-04-13 at 10.49.49 AM.png

🌟未使用KVO监听的对象


Screen Shot 2020-04-13 at 10.50.07 AM.png
🌟使用了KVO监听的对象
Screen Shot 2020-04-13 at 10.50.38 AM.png

🌟_NSSetIntValueAndNotify(_NSSet*ValueAndNotify)的内部实现:

- (void)setAge:(int)age
{
    _NSSetIntValueAndNotify();
}

// 伪代码
void _NSSetIntValueAndNotify()
{
    [self willChangeValueForKey:@"age"];
    [super setAge:age];
    [self didChangeValueForKey:@"age"];
}
- (void)didChangeValueForKey:(NSString *)key
{
    // 通知监听器,某某属性值发生了改变
    [oberser observeValueForKeyPath:key ofObject:self change:nil context:nil];
}

🌟调用willChangeValueForKey
🌟调用原来的setter实现
🌟调用didChangeValueForKey:
didChangeValueForKey:内部会调用oberser的observeValueForKeyPath:ofObject change:方法

上一篇下一篇

猜你喜欢

热点阅读