Objective-C Language IMP (implementation pointer)


Example

IMP is a C type referring to the implementation of a method, also known as an implementation pointer. It is a pointer to the start of a method implementation.

Syntax:

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

IMP is defined by:

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

To access this IMP, the message “methodForSelector” can be used.

Example 1:

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

The method adressed by the IMP can be called by dereferencing the IMP.

ImpDoSomething(myObject, @selector(doSomething));

So these calls are equal:

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

Example :2:

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

IMP methodImplementation  = [self methodForSelector:otherWaySelector];

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

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

Here, we call [NSObject methodForSelector which returns us a pointer to the C function that actually implements the method, which we can the subsequently call directly.