Archive for March, 2011

iOS 4.3: imp_implementationWithBlock()

Thursday, March 17th, 2011

In iOS 4.3, there are 3 rather low level functions in the runtime that provide a new kind of bridge between Objective-C and Blocks with a specific goal of facilitating the dynamic generation of method implementations.


IMP imp_implementationWithBlock(void *block);
void *imp_getBlock(IMP anImp);
BOOL imp_removeBlock(IMP anImp);

In particular, imp_implementationWithBlock() takes a block as a parameter, copies it to the heap, and returns a trampoline that allows the block to be used as the implementation — the IMP — of a method in any Objective-C class (as long as the block’s arguments and the method’s arguments are compatible).

Quite literally, this allows:

int j = 12;
IMP skewIMP = imp_implementationWithBlock(^(id _s, int k) { return k*j; });

Where skewIMP would then contain a function pointer that could be used as the IMP for a method declared like:

- (int)skew:(int)k;

Details on the flip side…. Read the rest of this entry »