KVO的实现机理,随便解释一下isa-swizzling

04/02/2018 08:25 上午 posted in  Runtime

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 data type is used for selectors.

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 of a method, also known as an implementation pointer. It's a pointer to a function returning 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指针。