Does objective-c have any kind of functionality which allows me to compose my own blocks or IMP
s on the fly?
By that I mean let me link together arbitrary code snippets into a single block (and then perform imp_implementationWithBlock
) or just get an assembled IMP
straight up.
(IMP) linkExistingBlock:LBExistingBlock With:^{
}
or
(IMP) linkExistingBlock:LBExistingBlock With:LBAnotherBlock
If you have two Blocks, just call them. Further, Blocks are objects, and can be put into NSArray
s. Then you can enumerate the array and invoke its contents.
for( dispatch_block_t block in arrayOfBlocks ){
block();
}
or
[arrayOfBlocks enumerateObjectsUsingBlock:^(dispatch_block_t block, NSUInteger idx, BOOL *stop) {
block();
}];
If you have IMP
s, those are just function pointers -- they can be put into a C array, or wrapped in NSValue
s and put into a Cocoa array. You just need to cast them before you try to call them.
For your example method signature:
- (dispatch_block_t)blockLinkingExistingBlock: (dispatch_block_t)firstBlock withBlock: (dispatch_block_t)secondBlock
{
dispatch_block_t linker = ^{ firstBlock(); secondBlock();};
// if compiling with ARC
return linker;
// otherwise
// return [[linker copy] autorelease];
}