IMP(實現指標)

IMP 是 C 型別,指的是方法的實現,也稱為實現指標。它是指向方法實現開始的指標。

句法:

id (*IMP)(id, SEL, …)

IMP 定義如下:

typedef id (*IMP)(id self,SEL _cmd,…);

要訪問此 IMP,可以使用訊息 methodForSelector

例 1:

IMP ImpDoSomething = [myObject methodForSelector:@selector(doSomething)];

IMP 所解決的方法可以通過解除引用 IMP 來呼叫。

ImpDoSomething(myObject, @selector(doSomething));

所以這些呼叫是相等的:

 myImpDoSomething(myObject, @selector(doSomething));
[myObject doSomething]
[myObject performSelector:mySelector]
[myObject performSelector:@selector(doSomething)]
[myObject performSelector:NSSelectorFromString(@"doSomething")];

示例:2:

SEL otherWaySelector = NSSelectorFromString(@“methodWithFirst:andSecond:andThird:");

IMP methodImplementation  = [self methodForSelector:otherWaySelector];

result = methodImplementation( self,
                          betterWaySelector,
                          first,
                          second,
                          third );

NSLog(@"methodForSelector : %@", result);

在這裡,我們呼叫[NSObject methodForSelector,它返回一個指向實際實現該方法的 C 函式的指標,我們可以隨後直接呼叫它。