浮于表面探究問題不失為一種方法,但是弄清楚本質(zhì)才是真正意義上的解決疑惑。
之前已經(jīng)寫過一篇博客- (IMP)methodForSelector與+ (IMP)instanceMethodForSelector的區(qū)別,通過測試代碼探索二者區(qū)別。本文將通過源代碼來剖析二者的區(qū)別。
methodForSelector分兩種情況,類函數(shù)和實例函數(shù),代碼實現(xiàn)如下:
//類函數(shù),通過遍歷類對象的函數(shù)列表,返回對應的結(jié)果
+ (IMP)methodForSelector:(SEL)sel {
if (!sel) [self doesNotRecognizeSelector:sel];
return class_getMethodImplementation(object_getClass((id)self), sel);
}
//實例函數(shù),通過遍歷實例對象的函數(shù)列表,返回對應的結(jié)果
- (IMP)methodForSelector:(SEL)sel {
if (!sel) [self doesNotRecognizeSelector:sel];
return class_getMethodImplementation([self class], sel);
}
通過代碼可以看出,methodForSelector函數(shù)實現(xiàn)是通過遍歷對象(實例對象和類對象)函數(shù)列表,返回對應的結(jié)果。
instanceMethodForSelector函數(shù)代碼實現(xiàn)如下:
//通過遍歷實例對象的函數(shù)列表,返回對應的結(jié)果
+ (IMP)instanceMethodForSelector:(SEL)sel {
if (!sel) [self doesNotRecognizeSelector:sel];
return class_getMethodImplementation(self, sel);
}
通過代碼可以看出,instanceMethodForSelector類函數(shù)是通過遍歷自身中的函數(shù)列表,返回對應的結(jié)果。換句話說,如果調(diào)用的一個元類,那么返回的是一個類實例的函數(shù),如果調(diào)用的是一個類,那么返回的就是實例對象的函數(shù)。
看了源代碼才覺得這樣的問題其實沒有太多研究的必要,源代碼已經(jīng)一目了然了。