珠玉在前 骄恶,此篇為轉(zhuǎn)載以及學(xué)習(xí)記錄
KVO
大神文章 : Mike Ash 早期深究 KVO
原理:神經(jīng)病院Objective-C Runtime出院第三天——如何正確使用Runtime
實(shí)現(xiàn):如何自己動(dòng)手實(shí)現(xiàn) KVO
總結(jié):
在官方文檔中,提到 KVO
只有以下內(nèi)容
Automatic key-value observing is implemented using a technique called *isa-swizzling*.
The `isa` pointer, as the name suggests, points to the object's class which maintains a dispatch table. This dispatch table essentially contains pointers to the methods the class implements, among other data.
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.
You should never rely on the `isa` pointer to determine class membership. Instead, you should use the `[class](https://developer.apple.com/documentation/objectivec/1418956-nsobject/1571949-class)` method to determine the class of an object instance.
可見 KVO
的實(shí)現(xiàn)使用了 isa swizzling
簡(jiǎn)單概述下 KVO 的實(shí)現(xiàn):
當(dāng)你觀察一個(gè)對(duì)象時(shí)柳弄,一個(gè)新的類會(huì)動(dòng)態(tài)被創(chuàng)建。這個(gè)類繼承自該對(duì)象的原本的類绒障,并重寫了被觀察屬性的 setter 方法统扳。
自然,重寫的 setter 方法會(huì)負(fù)責(zé)在調(diào)用原 setter 方法之前和之后贪婉,通知所有觀察對(duì)象值的更改反粥。
最后把這個(gè)對(duì)象的 isa 指針 ( isa 指針告訴 Runtime 系統(tǒng)這個(gè)對(duì)象的類是什么 ) 指向這個(gè)新創(chuàng)建的子類,對(duì)象就神奇的變成了新創(chuàng)建的子類的實(shí)例。
原來(lái)才顿,這個(gè)中間類莫湘,繼承自原本的那個(gè)類。不僅如此郑气,Apple 還重寫了 -class 方法幅垮,企圖欺騙我們這個(gè)類沒(méi)有變,就是原本那個(gè)類尾组。