在Objective-C
里面贴见,方法分為實(shí)例方法和動(dòng)態(tài)方法,但是不管是實(shí)例方法還是動(dòng)態(tài)方法躲株,最終都會(huì)變?yōu)橐痪浜瘮?shù)調(diào)用objc_msgSend
片部;通常給對(duì)象發(fā)送一個(gè)未知消息的時(shí)候,程序往往會(huì)崩潰霜定,并提示unrecognized selector send to instance
档悠,那么runtime是如何實(shí)現(xiàn)方法的調(diào)用呢?
首先要知道望浩,Objective-C
的繼承體系是什么樣子的辖所?
在方法的調(diào)用的時(shí)候,實(shí)際上磨德,實(shí)例方法是存方法類中缘回,類對(duì)象是一個(gè)單例對(duì)象,在內(nèi)存中只有一份典挑,而類方法是存放在元類中切诀。
斷點(diǎn)調(diào)試方法調(diào)用
// 創(chuàng)建對(duì)象,并發(fā)送消息
Person *p = [[Person alloc] init];
[p testInstanceMethod]; // add a breakpoint
在這個(gè)方法打上斷點(diǎn)搔弄,進(jìn)入堆棧信息
點(diǎn)擊
control
+step into
就可以進(jìn)入堆棧信息
在objc_msgSend
處添加斷點(diǎn)幅虑,進(jìn)入objc_msgSend
函數(shù)中查看調(diào)用的方法:
這里調(diào)用了_objc_msgSend_uncached
,因?yàn)檫@里是第一次調(diào)用,猜想如果是之后調(diào)用的話顾犹,會(huì)直接調(diào)用緩存倒庵,進(jìn)入這個(gè)函數(shù)里面查看:
這里會(huì)調(diào)用_class_lookupMethodAndLoadCache3
這樣一個(gè)函數(shù)褒墨,然后在runtime的源碼里面搜索,找到它的實(shí)現(xiàn)
IMP _class_lookupMethodAndLoadCache3(id obj, SEL sel, Class cls)
{
return lookUpImpOrForward(cls, sel, obj,
YES/*initialize*/, NO/*cache*/, YES/*resolver*/);
}
這里的核心就是這個(gè)方法lookUpImpOrForward
擎宝,它所做的事情就是郁妈,查找cls的方法列表,匹配sel绍申,找到對(duì)應(yīng)的函數(shù)實(shí)現(xiàn)IMP并返回噩咪,否則,沿著繼承鏈查找父類的方法列表极阅,如果還是沒有胃碾,會(huì)進(jìn)入動(dòng)態(tài)方法解析,看有沒有動(dòng)態(tài)添加方法筋搏,如果有仆百,就將sel和添加的這個(gè)方法實(shí)現(xiàn)綁定,并添加到緩存中奔脐,否則俄周,進(jìn)入消息轉(zhuǎn)發(fā)。
// 1.
// Try this class's method lists.
{
// 查找這個(gè)類的方法列表
Method meth = getMethodNoSuper_nolock(cls, sel);
if (meth) {
// 緩存起來
log_and_fill_cache(cls, meth->imp, sel, inst, cls);
imp = meth->imp;
goto done;
}
}
// 2.
for (Class curClass = cls->superclass;
curClass != nil;
curClass = curClass->superclass)
{ // 查詢父類的方法列表
// 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;
}
}
// 3.
// No implementation found. Try method resolver once.
if (resolver && !triedResolver) {
runtimeLock.unlock();
// 進(jìn)入動(dòng)態(tài)方法解析
_class_resolveMethod(cls, sel, inst);
runtimeLock.lock();
// Don't cache the result; we don't hold the lock so it may have
// changed already. Re-do the search from scratch instead.
triedResolver = YES;
goto retry;
}
// 4.
// No implementation found, and method resolver didn't help.
// Use forwarding.
// 進(jìn)入消息轉(zhuǎn)發(fā)流程
imp = (IMP)_objc_msgForward_impcache;
cache_fill(cls, sel, imp, inst);
在動(dòng)態(tài)方法解析中髓迎,需要實(shí)現(xiàn)這樣兩個(gè)方法:
+resolveClassMethod // 類方法
+resolveInstanceMethod // 實(shí)例方法
void sendMsg(id self, SEL _cmd) {
NSLog(@"來了");
}
+ (BOOL)resolveInstanceMethod:(SEL)sel {
NSString *methodName = NSStringFromSelector(sel);
if ([methodName isEqualToString:@"testInstanceMethod"]) {
return class_addMethod([self class], sel, (IMP)sendMsg, "v@:");
}
return NO;
}
常見面試題
1.
NSLog(@"%@", [self class]); // objc_mgsSend
// 會(huì)構(gòu)造一個(gè)結(jié)構(gòu)體(self, getSuperClass)
// 接收消息的對(duì)象還是self 所以打印出來的時(shí)候是一樣的
NSLog(@"%@", [super class]); // objc_msgSendSuper
這里需要注意的是 [super class]
的調(diào)用實(shí)際上是調(diào)用的objc_msgSendSuper
這個(gè)函數(shù)峦朗,
* id objc_msgSendSuper(struct objc_super *super, SEL _cmd,...);
*
* struct objc_super {
* id receiver;
* Class class;
* };
官方文檔解釋:
When it encounters a method call, the compiler generates a call to one of the functions objc_msgSend, objc_msgSend_stret, objc_msgSendSuper, or objc_msgSendSuper_stret. Messages sent to an object’s superclass (using the super keyword) are sent using objc_msgSendSuper; other messages are sent using objc_msgSend. Methods that have data structures as return values are sent using objc_msgSendSuper_stret and objc_msgSend_stret.
super
A pointer to an objc_super data structure. Pass values identifying the context the message was sent to, including the instance of the class that is to receive the message and the superclass at which to start searching for the method implementation.
op
A pointer of type SEL. Pass the selector of the method that will handle the message.
...
A variable argument list containing the arguments to the method.
super
是一個(gè)結(jié)構(gòu)體,那么在調(diào)用class方法的時(shí)候排龄,接受的對(duì)象其實(shí)還是self甚垦,所以兩者最終打印的結(jié)構(gòu)都是當(dāng)前的類對(duì)象。
2.
NSLog(@"----%d", [[self class] isKindOfClass:[SubClass class]]);
NSLog(@"----%d", [self isKindOfClass:[SubClass class]]);
isKindOfClass
比較的是什么涣雕?艰亮,首先這個(gè)調(diào)用的是類方法,進(jìn)入方法實(shí)現(xiàn)
+ (BOOL)isKindOfClass:(Class)cls {
// self: SubClass 類對(duì)象
// object_getClass:
// 1.如果self是類對(duì)象:得到的是元類對(duì)象
// 2.如果self是對(duì)象:得到的是類對(duì)象
for (Class tcls = object_getClass((id)self); tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}
Class object_getClass(id obj)
{
if (obj) return obj->getIsa();
else return Nil;
}
如果是 [obj isKindOfClass:[SubClass class]]
,obj是實(shí)例對(duì)象挣郭,調(diào)用的是
- (BOOL)isKindOfClass:(Class)cls {
// tcls: 類對(duì)象
// tcls == cls 比較的就是cls是不是類對(duì)象
for (Class tcls = [self class]; tcls; tcls = tcls->superclass) {
if (tcls == cls) return YES;
}
return NO;
}