八面玲珑的 objc_msgSend

此函数是消息发送必经之路,但只要一提 objc_msgSend,都会说它的伪代码如下或类似的逻辑,反正就是获取 IMP 并调用:


id objc_msgSend(id self, SEL _cmd, ...) {
Class class = object_getClass(self);
IMP imp = class_getMethodImplementation(class, _cmd);
return imp ? imp(self, _cmd, ...) : 0;
}

回顾 objc_msgSend 伪代码

回过头来会发现 objc_msgSend 的伪代码描述得很传神啊,因为class_getMethodImplementation 的实现如下:

IMP class_getMethodImplementation(Class cls, SEL sel)
{
IMP imp;
if (!cls || !sel) return nil;
imp = lookUpImpOrNil(cls, sel, nil, YES/*initialize*/, YES/*cache*/, YES/*resolver*/);
// Translate forwarding function to C-callable external version
if (!imp) {
return _objc_msgForward;
}
return imp;
} Objective-C 消息发送与转发机制原理(摘)-LMLPHP消息发送与转发路径流程图
 
http://yulingtianxia.com/blog/2016/06/15/Objective-C-Message-Sending-and-Forwarding/
05-11 15:21