在平時(shí)開(kāi)發(fā)中看似簡(jiǎn)單的方法調(diào)用,其實(shí)底層是做了多重操作的,只是我們不能具體看到,在此大致說(shuō)一下objc_msgSend的執(zhí)行流程,objc_msgSend的執(zhí)行流程大致可以分為3個(gè)階段
1.消息發(fā)送階段
2.動(dòng)態(tài)方法解析階段
3.消息轉(zhuǎn)發(fā)階段
消息發(fā)送階段
retry:
runtimeLock.assertReading();
// Try this class's cache.
imp = cache_getImp(cls, sel);
if (imp) goto done;
// Try this class's method lists.
{
Method meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, cls);
imp = meth->imp;
goto done;
}
}
// Try superclass caches and method lists.
{
unsigned attempts = unreasonableClassCount();
for (Class curClass = cls->superclass;
curClass != nil;
curClass = curClass->superclass)
{
// Halt if there is a cycle in the superclass chain.
if (--attempts == 0) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
if (imp) {
if (imp != (IMP)_objc_msgForward_impcache) {
// Found the method in a superclass. Cache it in this class.
log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
}
// Superclass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
}
}
//沒(méi)有找到,就會(huì)嘗試消息解析
// No implementation found. Try method resolver once.
if (resolver && !triedResolver) {
runtimeLock.unlockRead();
_class_resolveMethod(cls, sel, inst);
runtimeLock.read();
// Don't cache the result; we don't hold the lock so it may have
// changed already. Re-do the search from scratch instead.
//判斷是否解析過(guò)
triedResolver = YES;
goto retry;
}
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
done:
runtimeLock.unlockRead();
return imp;
通過(guò)上面的源碼可以看到,通過(guò)isa找到自己的類(lèi)對(duì)象的緩存Try this class's cache和方法列表Try this class's method lists中查找,如果找到則goto done,結(jié)束查找。
如果沒(méi)有找到則會(huì)從父類(lèi)的緩存和方法列表中查找Try superclass caches and method lists. 會(huì)有一個(gè)for循環(huán)for (Class curClass = cls->superclass; curClass != nil; curClass = curClass->superclass),拿到當(dāng)前類(lèi)的父類(lèi)給當(dāng)前類(lèi),for循環(huán)就是一層一層拿到父類(lèi),找到父類(lèi)從父類(lèi)中緩存中查找imp= cache_getImp(curClass, sel),如果有緩存則會(huì)將緩存填充到緩存中去log_and_fill_cache(cls, imp, sel, inst, curClass),此時(shí)是填充到消息類(lèi)對(duì)象接受者的類(lèi)對(duì)象中去,舉個(gè)栗子:有一個(gè)類(lèi)TestGoodStudent 繼承自TestPerson類(lèi),TestGoodStudent *tt = [[TestGoodStudent alloc] init];當(dāng)我對(duì)TestGoodStudent類(lèi)創(chuàng)建的類(lèi)對(duì)象tt進(jìn)行調(diào)用父類(lèi)的test方法時(shí),則會(huì)從TestPerson類(lèi)中找到test方法,并將test方法緩存到TestGoodStudent的類(lèi)對(duì)象中去然后 goto done。
如果父類(lèi)緩存中沒(méi)有找到,則會(huì)去方法列表中查找,找到之后緩存到自己緩存中去,原理同緩存查找,找到之后 goto done
如果消息發(fā)送都沒(méi)有找到,會(huì)向下走
//沒(méi)有找到,就會(huì)嘗試消息解析resolver
// No implementation found. Try method resolver once.
流程圖如下:

動(dòng)態(tài)方法解析階段
動(dòng)態(tài)方法解析:當(dāng)在自己的緩存和所有父類(lèi)的緩存中都沒(méi)有找到調(diào)用的方法,自己的rw_t和父類(lèi)的rw_t都沒(méi)有找到方法,則就會(huì)進(jìn)行動(dòng)態(tài)方法解析。
另外是否進(jìn)行動(dòng)態(tài)方法解析還會(huì)根據(jù)triedResolver這個(gè)Bool值進(jìn)行判斷,沒(méi)有解析過(guò),就會(huì)進(jìn)行動(dòng)態(tài)解析,只要進(jìn)行解析過(guò)一遍,則triedResolver就會(huì)標(biāo)記為YES,就不會(huì)再進(jìn)行解析,動(dòng)態(tài)解析會(huì)根據(jù)類(lèi)是類(lèi)對(duì)象還是原類(lèi)對(duì)象進(jìn)行調(diào)用_class_resolveInstanceMethod和_class_resolveClassMethod,可以通過(guò)查看源碼中objc-runtime-new.mm類(lèi)中_class_lookupMethodAndLoadCache3方法
IMP lookUpImpOrForward(Class cls, SEL sel, id inst,
bool initialize, bool cache, bool resolver)
{
IMP imp = nil;
bool triedResolver = NO;
runtimeLock.assertUnlocked();
// Optimistic cache lookup
if (cache) {
imp = cache_getImp(cls, sel);
if (imp) return imp;
}
// runtimeLock is held during isRealized and isInitialized checking
// to prevent races against concurrent realization.
// runtimeLock is held during method search to make
// method-lookup + cache-fill atomic with respect to method addition.
// Otherwise, a category could be added but ignored indefinitely because
// the cache was re-filled with the old value after the cache flush on
// behalf of the category.
runtimeLock.read();
if (!cls->isRealized()) {
// Drop the read-lock and acquire the write-lock.
// realizeClass() checks isRealized() again to prevent
// a race while the lock is down.
runtimeLock.unlockRead();
runtimeLock.write();
realizeClass(cls);
runtimeLock.unlockWrite();
runtimeLock.read();
}
if (initialize && !cls->isInitialized()) {
runtimeLock.unlockRead();
_class_initialize (_class_getNonMetaClass(cls, inst));
runtimeLock.read();
// If sel == initialize, _class_initialize will send +initialize and
// then the messenger will send +initialize again after this
// procedure finishes. Of course, if this is not being called
// from the messenger then it won't happen. 2778172
}
retry:
runtimeLock.assertReading();
// Try this class's cache.
imp = cache_getImp(cls, sel);
if (imp) goto done;
// Try this class's method lists.
{
Method meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, cls);
imp = meth->imp;
goto done;
}
}
// Try superclass caches and method lists.
{
unsigned attempts = unreasonableClassCount();
for (Class curClass = cls->superclass;
curClass != nil;
curClass = curClass->superclass)
{
// Halt if there is a cycle in the superclass chain.
if (--attempts == 0) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
if (imp) {
if (imp != (IMP)_objc_msgForward_impcache) {
// Found the method in a superclass. Cache it in this class.
log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
}
// Superclass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
}
}
// No implementation found. Try method resolver once.
if (resolver && !triedResolver) {
runtimeLock.unlockRead();
_class_resolveMethod(cls, sel, inst);
runtimeLock.read();
// Don't cache the result; we don't hold the lock so it may have
// changed already. Re-do the search from scratch instead.
//判斷是否解析過(guò)
triedResolver = YES;
goto retry;
}
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
done:
runtimeLock.unlockRead();
return imp;
}
如果沒(méi)有實(shí)現(xiàn)resolveInstanceMethod,但是還會(huì)triedResolver=YES, 則goto rety
再次進(jìn)行進(jìn)入 if (resolver && !triedResolver), 條件不滿足,則程序會(huì)順序執(zhí)行,會(huì)走_(dá)objc_msgForward_impcache進(jìn)行消息轉(zhuǎn)發(fā)
retry:
runtimeLock.assertReading();
// Try this class's cache.
imp = cache_getImp(cls, sel);
if (imp) goto done;
// Try this class's method lists.
{
Method meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, cls);
imp = meth->imp;
goto done;
}
}
// Try superclass caches and method lists.
{
unsigned attempts = unreasonableClassCount();
for (Class curClass = cls->superclass;
curClass != nil;
curClass = curClass->superclass)
{
// Halt if there is a cycle in the superclass chain.
if (--attempts == 0) {
_objc_fatal("Memory corruption in class list.");
}
// Superclass cache.
imp = cache_getImp(curClass, sel);
if (imp) {
if (imp != (IMP)_objc_msgForward_impcache) {
// Found the method in a superclass. Cache it in this class.
log_and_fill_cache(cls, imp, sel, inst, curClass);
goto done;
}
else {
// Found a forward:: entry in a superclass.
// Stop searching, but don't cache yet; call method
// resolver for this class first.
break;
}
}
// Superclass method list.
Method meth = getMethodNoSuper_nolock(curClass, sel);
if (meth) {
log_and_fill_cache(cls, meth->imp, sel, inst, curClass);
imp = meth->imp;
goto done;
}
}
}
// No implementation found. Try method resolver once.
if (resolver && !triedResolver) {
runtimeLock.unlockRead();
_class_resolveMethod(cls, sel, inst);
runtimeLock.read();
// Don't cache the result; we don't hold the lock so it may have
// changed already. Re-do the search from scratch instead.
//判斷是否解析過(guò)
triedResolver = YES;
goto retry;
}
// No implementation found, and method resolver didn't help.
// Use forwarding.
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
done:
runtimeLock.unlockRead();
return imp;
測(cè)試Demo中,動(dòng)態(tài)方法實(shí)現(xiàn)了在resolveInstanceMethod中添加了other方法
+ (BOOL)resolveInstanceMethod:(SEL)sel
{
if (sel == @selector(test)) {
// 獲取其他方法
Method method = class_getInstanceMethod(self, @selector(other));
// 動(dòng)態(tài)添加test方法的實(shí)現(xiàn)
//method_getImplementation 得到imp
//method_getTypeEncoding 得到type
class_addMethod(self, sel,
method_getImplementation(method),
method_getTypeEncoding(method));
// 返回YES代表有動(dòng)態(tài)添加方法
return YES;
}
return [super resolveInstanceMethod:sel];
}
動(dòng)態(tài)方法解析流程如下:

消息轉(zhuǎn)發(fā)階段
當(dāng)調(diào)用一個(gè) NSObject 對(duì)象不存在的方法時(shí),并不會(huì)馬上拋出異常,而是會(huì)經(jīng)過(guò)多層轉(zhuǎn)發(fā),層層調(diào)用對(duì)象的:-resolveInstanceMethod: --> -forwardingTargetForSelector: --> -methodSignatureForSelector: --> -forwardInvocation: 等方法,其中最后 -forwardInvocation: 是會(huì)有一個(gè) NSInvocation 對(duì)象,這個(gè) NSInvocation 對(duì)象保存了這個(gè)方法調(diào)用的所有信息,包括 Selector 名,參數(shù)和返回值類(lèi)型,最重要的是有 所有參數(shù)值 ,可以從這個(gè) NSInvocation 對(duì)象里拿到調(diào)用的所有參數(shù)值。
NSInvocation封裝了一個(gè)方法調(diào)用,包括:方法調(diào)用者、方法名、方法參數(shù)
anInvocation.target 方法調(diào)用者
anInvocation.selector 方法名
[anInvocation getArgument:NULL atIndex:0]
參考Demo,在MJPerson中沒(méi)有實(shí)現(xiàn)test方法,則在main.m中調(diào)用
int main(int argc, const char * argv[]) {
@autoreleasepool {
MJPerson *person = [[MJPerson alloc] init];
[person test];
}
return 0;
}
調(diào)用test時(shí),因?yàn)镸JPerson沒(méi)有實(shí)現(xiàn)test方法,則就會(huì)進(jìn)行消息轉(zhuǎn)發(fā),調(diào)用forwardingTargetForSelector,如果forwardingTargetForSelector中
- (id)forwardingTargetForSelector1:(SEL)aSelector
{
if (aSelector == @selector(test)) {
return [[MJCat alloc] init];
}
return [super forwardingTargetForSelector:aSelector];
}
這樣會(huì)調(diào)用MJCat 的test方法, 如果沒(méi)有實(shí)現(xiàn)test,則會(huì)調(diào)用methodSignatureForSelector
- (id)forwardingTargetForSelector:(SEL)aSelector
{
if (aSelector == @selector(test)) {
return nil;
}
return [super forwardingTargetForSelector:aSelector];
}
如果直接返回nil,則會(huì)調(diào)用methodSignatureForSelector , 并在該方法中返回一個(gè)方法簽名,如果方法簽名為空,則是不想處理該方法,會(huì)調(diào)用doesNotRecongnizeSector
整理后的源碼如下
int __forwarding__(void *frameStackPointer, int isStret) {
id receiver = *(id *)frameStackPointer;
SEL sel = *(SEL *)(frameStackPointer + 8);
const char *selName = sel_getName(sel);
Class receiverClass = object_getClass(receiver);
// 調(diào)用 forwardingTargetForSelector:
if (class_respondsToSelector(receiverClass, @selector(forwardingTargetForSelector:))) {
id forwardingTarget = [receiver forwardingTargetForSelector:sel];
if (forwardingTarget && forwardingTarget != receiver) {
return objc_msgSend(forwardingTarget, sel, ...);
}
}
// 調(diào)用 methodSignatureForSelector 獲取方法簽名后再調(diào)用 forwardInvocation
if (class_respondsToSelector(receiverClass, @selector(methodSignatureForSelector:))) {
NSMethodSignature *methodSignature = [receiver methodSignatureForSelector:sel];
if (methodSignature && class_respondsToSelector(receiverClass, @selector(forwardInvocation:))) {
NSInvocation *invocation = [NSInvocation _invocationWithMethodSignature:methodSignature frame:frameStackPointer];
[receiver forwardInvocation:invocation];
void *returnValue = NULL;
[invocation getReturnValue:&value];
return returnValue;
}
}
if (class_respondsToSelector(receiverClass,@selector(doesNotRecognizeSelector:))) {
[receiver doesNotRecognizeSelector:sel];
}
// The point of no return.
kill(getpid(), 9);
}
消息轉(zhuǎn)發(fā)流程如下:

objc_msgSend 編譯報(bào)錯(cuò)
在使用objc_msgSend的時(shí)候發(fā)現(xiàn)會(huì)報(bào)如下錯(cuò)誤,

究其原因是因?yàn)檫\(yùn)行時(shí)代碼里有一個(gè)宏定義

這個(gè)宏定義在objc-api.h里有它的原型

它其實(shí)是一條預(yù)編譯指令,所以在Xcode的buildSettings里有了對(duì)應(yīng)的選項(xiàng),通過(guò)設(shè)置讓這個(gè)宏定義不生效,上面的message.h里就能走到else里了,objc_msgSend 才能像c函數(shù)那樣使用。
在這段注釋中
These functions must be cast to an appropriate function pointer type
before being called.
這句注釋的異地就是這個(gè)函數(shù)在使用之前要轉(zhuǎn)為合適的函數(shù)指針來(lái)使用,看起來(lái)有點(diǎn)怪怪的,但是存在是合理的。
說(shuō)下怎么辦?
使用運(yùn)行時(shí)函數(shù) objc_msgSend 的時(shí)候要把Xcode里這項(xiàng)配置關(guān)掉,才能使用C形式的函數(shù)調(diào)用:

這樣就可以了~~