導(dǎo)語(yǔ)
今天在編碼的時(shí)候,無(wú)意間看到了- (IMP)methodForSelector函數(shù),讓我聯(lián)想到平時(shí)經(jīng)常用的+ (IMP)instanceMethodForSelector函數(shù)。這兩個(gè)函數(shù)從字面意思來(lái)看很相近,但是既然同時(shí)存在,二者一定存在區(qū)別。于是,結(jié)合開發(fā)文檔和代碼測(cè)試,進(jìn)行了一些探索。
+ (IMP)instanceMethodForSelector:(SEL)aSelector
功能概述:根據(jù)指定的sSelector,遍歷類的實(shí)例方法列表,返回對(duì)應(yīng)的函數(shù)指針。
有兩個(gè)地方需要注意:
一、這是一個(gè)類函數(shù),調(diào)用者是一個(gè)Class;
二、函數(shù)返回結(jié)果的類型是實(shí)例函數(shù)指針,而非類函數(shù)指針。
代碼測(cè)試:
@interface TestObject : NSObject
@end
@implementation TestObject
- (void)testFun
{
}
int main(int argc, const char * argv[])
{
IMP p = [TestObject instanceMethodForSelector:@selector(testFun)];
NSLog(@"%p " , p);
return 0;
}
輸出結(jié)果:
2015-12-21 16:17:02.217 TestProject[2916:166056] 0x100000ad0
猜想:該函數(shù)內(nèi)部實(shí)現(xiàn)過程中創(chuàng)建了一個(gè)實(shí)例對(duì)象,然后遍歷實(shí)例對(duì)象的函數(shù)列表,搜索指定的函數(shù)名對(duì)應(yīng)的函數(shù)指針。
- (IMP)methodForSelector:(SEL)aSelector
功能概述:根據(jù)指定的sSelector,返回調(diào)用者函數(shù)列表中對(duì)應(yīng)的函數(shù)指針。
有兩個(gè)地方需要注意:
一、這是一個(gè)實(shí)例對(duì)象函數(shù),調(diào)用者可以是實(shí)例對(duì)象也可以是類對(duì)象(在Object C中,類本身也是對(duì)象)
二、函數(shù)返回結(jié)果的類型可能是實(shí)例函數(shù)指針,也可能是類函數(shù)指針。
代碼測(cè)試:
int main(int argc, const char * argv[])
{
TestObject obj = [TestObject new];
IMP pObj = [obj methodForSelector:@selector(testFun)];
IMP pClass = [TestObject methodForSelector:@selector(testFun)];
NSLog(@"%p" , pObj);
NSLog(@"%p" , pClass);
return 0;
}
輸出結(jié)果:
2015-12-21 16:39:12.711 TestProject[3002:179046] 0x100000ad0
2015-12-21 16:39:12.713 TestProject[3002:179046] 0x7fff8878bd40
結(jié)論:根據(jù)上面的輸出結(jié)果,可以看出實(shí)例對(duì)象調(diào)用- (IMP)methodForSelector與類調(diào)用+ (IMP)instanceMethodForSelector輸出結(jié)果是一致的,都是實(shí)例對(duì)象的函數(shù)指針;而類對(duì)象調(diào)用- (IMP)methodForSelector輸出結(jié)果則是類本身的類函數(shù)指針。
綜述:這兩個(gè)函數(shù)除了類型上的區(qū)別之外,- (IMP)methodForSelector函數(shù)的使用范圍更廣一些,既可以獲得實(shí)例對(duì)象函數(shù)指針,又能獲去類對(duì)象函數(shù)指針。此外,+ (IMP)instanceMethodForSelector更像是對(duì)- (IMP)methodForSelector的一次封裝,用來(lái)更便捷地獲取實(shí)例對(duì)象的函數(shù)指針。