KVO的實現機理,隨便解釋一下isa-swizzling
isa-swizzling
isa, is a kind of
swizzling, 混合,攪合。
KVO的基礎KVC。
KVC主要通過isa-swizzling,來實現。
[site setValue:@"sitename" forKey:@"name"];
編譯器處理成:
SEL sel = sel_get_uid ("setValue:forKey:");
IMP method = objc_msg_lookup (site->isa,sel);
method(site, sel, @"sitename", @"name");
Selectors
Selectors are the run-time system's identifier for a method. The SEL
The sel_get_uid() function can be used to get a method's selector from it's name:
objc_msg_lookup
If we want to get an IMP
using the Objective-C runtime functions, then use objc_msg_lookup(id,SEL)
on the GNU runtime.
What is an IMP? How do I get one?
IMP
is a C type referring to the implementation
id
, and with self
and a method selector (available inside method definitions as the variable _cmd
) as the first arguments:
id (*IMP)(id, SEL, ...);
With NSObject, you can obtain the IMP
for a given method by doing:
IMP imp=[obj methodForSelector:@selector(message)];
For Object, do:
IMP imp=[obj methodFor:@selector(message)];
How do I send a message given an IMP?
Dereference it, as with a C function pointer:
id anObject, theResult; IMP someImp; SEL aSelector; // ... theResult=someImp(anObject,aSelector);
=================
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.
Instead of relying on the isa pointer your application should use the class method to determine the class of an object instance.
鍵-值觀察實現細節
自動鍵-值觀察是由叫isa-swizzling的技術實現的。
isa指標,如其名稱所指,指向維護分發表的物件的類。該分發表實際上包含了指向實現類中的方法的指標,和其它資料。
當某個物件的屬性註冊了中觀察者時,當該被觀察物件的isa指標被修改為指向一箇中間類,而不是真實的類。因此isa指標的值並不一定反映例項的實際類。
你的程式應當使用class方法來確定例項物件的類,而不是依賴於isa指標。