KVO

作者: 大鹅ne | 来源:发表于2020-04-13 11:08 被阅读0次

    🌟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:方法

    相关文章

      网友评论

          本文标题:KVO

          本文链接:https://www.haomeiwen.com/subject/vtfgmhtx.html