KVO 实现细节或原理

Key-Value Observing Implementation Details

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

自动 KVO 实现使用 isa-swizzling 技术

When an observer is registered for an attribute of an object the isa pointer of the observed object is modified, pointing to an intermediate class rather than at the true class. As a result the value of the isa pointer does not necessarily reflect the actual class of the instance.

当观察者注册一个属性时,被观察者的 isa 指针会被修改,指向一个中间类,而不是实际的类。

当观察者注册了 key,被观察者 Class 到底发生了哪些改变?

原文

设:被观察者为 KVOObject 类,被观察属性为 name

  • 动态生成一个被观察者中间类 NSKVONotifying_KVOObject,继承于 KVOObject;
  • 实例对象的 isa 指针指向 NSKVONotifying_KVOObject;
  • NSKVONotifying_KVOObject 重写 setName: 方法,加入了 -willChangeValueForKey: 和 -didChangeValueForKey: 调用;
  • 重写了 Class 方法,返回 KVOObject Class 名;
  • 新增了 _isKVOA 方法,用来判断当前类是否是 KVO 动态生成的类;
被观察者所属的类

You should never rely on the isa pointer to determine class membership. Instead, you should use the class method to determine the class of an object instance.

判断被观察者所属的类,应该用 [obj class] class 方法。不要用 isa 指针来判断,如:object_getClass(obj),object_getClass 是通过 isa 来查找 class,并返回 class name 的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值