Looking for objective-c Keywords? Try Ask4Keywords

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