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 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指针。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值