KVO 底层原理

238 阅读1分钟

KVO API文档如下:

Automatic key-value observing is implemented using a technique called isa-swizzling… When an observer is registered 
foran attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate 
classrather than at the 
trueclass…

实现原理: KVO是通过isa-swizzling技术实现的(依赖于Runtime),当观察某个类的属性时,系统通过运行时动态创建一个基于类的子类,并将isa指向新创建的动态子类(新创建的类名格式:NSKVONotifying_xxx),同时,会将该属性的setter方法进行重写(imp指针改变),从而激活键值通知机制。KVO的键值观察通知依赖与NSObject的两个方法:willChangeValueForKey:和didChangeValueForKey:,在存取数值的前后分别调用2个方法: 被观察属性发生改变之前,willChangeValueForkey:被调用,通知系统该keyPath的属性值即将变更;当改变发生后,didChangeValueForkey:被调用,通知系统该keyPath的属性值已经变更;之后,observeValueForKey:ofObject:context:也会被调用。动态添加class,使其与原类更像,动态添加析构方法dealloc,也添加一个标记isKVOA。