探究iOS中的KVO底层实现

什么是KVO

Key-value observing provides a mechanism that allows objects to be notified of changes to specific properties of other objects.

KVO(Key-value observing)是键值观察的简写,是Objective-C对观察者设计模式的实现,是Cocoa Binding的基础,通常用于Model层与Controller层之间的通信。

基本使用

在iOS开发中使用KVO主要分为以下三个步骤:

In order to receive key-value observing notifications for a property, three things are required:
1.The observed class must be key-value observing compliant for the property that you wish to observe.
2. You must register the observing object with the observed object, using the method
addObserver:forKeyPath:options:context:.
3. The observing class must implement observeValueForKeyPath:ofObject:change:context:

  • 添加观察者

    - (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(nullable void *)context;
    
  • 实现监听方法

    - (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context;
    
  • 移除观察者

    - (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath;
    

底层实现

Automatic key-value observing is implemented using a technique called isa-swizzling.

KVO建立在KVC基础之上,必须遵循KVC的编码规范。KVO的底层实现是利用isa-swizzling技术,在程序运行过程中,通过Runtime API动态生成一个子类(NSKVONotifying_A),并且让实例对象的isa指向这个全新的子类,当修改实例对象的属性时,会调用Foundation的_NSSetXXXValueAndNotify函数。


举个实际的栗子来追踪一下KVO的底层机制及流程。创建一个LMPerson类,对p1的age进行键值观察,对p2不进行键值观察,追踪对p1添加KVO后p1、p2各自的isa、IMP等信息的变化。

- (void)addObserver {
    NSKeyValueObservingOptions options = NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld;
    [self.p1 addObserver:self forKeyPath:@"age" options:options context:NULL];
}

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

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if (object == self.p1 && [keyPath isEqualToString:@"age"]) {
        NSLog(@"keyPath = %@,object = %@,change = %@,context = %@",keyPath,object,change,context);
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

可以发现对p1添加KVO后,它的isa指向了一个全新的子类NSKVONotifying_LMPerson。
KVO1
而且它的setAge:方法的IMP指向了Foundation框架中的一个函数:_NSSetUnsignedLongLongValueAndNotify(由于age声明为了NSUInteger类型,可以猜想Foundation框架中还有很多类似_NSSetXXXValueAndNotify形式的函数,可利用终端nm命令查看Foundation框架中的符号函数或者将Foundation的MachO文件放入MachOView中查看)
KVO2
利用Runtime API分别打印p1添加KVO前后p1、p2的Class中存放的实例方法

- (void)printMethodForClass:(Class)cls {
    
    unsigned int count;
    Method *methodList = class_copyMethodList(cls, &count);
    
    NSMutableString *methodNames = [NSMutableString new];
    [methodNames appendFormat:@"%@---",cls];
    
    for (int index = 0; index < count; index++) {
        Method method = methodList[index];
        
        NSString *tempMethodName = NSStringFromSelector(method_getName(method));
        [methodNames appendString:tempMethodName];
        [methodNames appendString:@"|"];
    }
    
    NSLog(@"%@",methodNames);
    
    free(methodList);
}

p1的Class中会多几个方法:class、dealloc、_isKVOA
KVO3
之所以重写class方法,是因为想隐藏一些内部细节,让外界以为指向了同一个类。对某个对象的属性进行KVO操作,通过setter方法或者KVC的方式对属性进行修改时会自动触发对象的willChangeValueForKey:方法和didChangeValueForKey:方法。调用顺序如下:

  1. willChangeValueForKey:
  2. 父类的setter方法
  3. didChangeValueForKey:(内部会调用监听器的监听方法observeValueForKeyPath: ofObject:change:context:)KVO4

总结

本文简单回顾了KVO的基本使用,探索了KVO的底层实现。iOS开发中常使用KVO可以方便的监听属性变化,比如监听WebView的ContentSize,但是使用系统的API也有不好的地方,比如对同一个属性的观察者移除两次会导致崩溃、不支持Block等。在实际开发中推荐使用Facebook开源的KVOController ,具有轻量、线程安全、简洁的API的优点,支持Block等。最后附上本文Demo地址。

参考资料:

Key-Value Observing Programming Guide

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值