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 函数的指针,我们可以随后直接调用它。