什么是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。
而且它的setAge:方法的IMP指向了Foundation框架中的一个函数:_NSSetUnsignedLongLongValueAndNotify(由于age声明为了NSUInteger类型,可以猜想Foundation框架中还有很多类似_NSSetXXXValueAndNotify形式的函数,可利用终端nm命令查看Foundation框架中的符号函数或者将Foundation的MachO文件放入MachOView中查看)
利用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
之所以重写class方法,是因为想隐藏一些内部细节,让外界以为指向了同一个类。对某个对象的属性进行KVO操作,通过setter方法或者KVC的方式对属性进行修改时会自动触发对象的willChangeValueForKey:方法和didChangeValueForKey:方法。调用顺序如下:
- willChangeValueForKey:
- 父类的setter方法
- didChangeValueForKey:(内部会调用监听器的监听方法observeValueForKeyPath: ofObject:change:context:)
总结
本文简单回顾了KVO的基本使用,探索了KVO的底层实现。iOS开发中常使用KVO可以方便的监听属性变化,比如监听WebView的ContentSize,但是使用系统的API也有不好的地方,比如对同一个属性的观察者移除两次会导致崩溃、不支持Block等。在实际开发中推荐使用Facebook开源的KVOController ,具有轻量、线程安全、简洁的API的优点,支持Block等。最后附上本文Demo地址。