Question

Question

Does objective-c have any kind of functionality which allows me to compose my own blocks or IMPs 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.

Pseudocode

(IMP) linkExistingBlock:LBExistingBlock With:^{

}

or

(IMP) linkExistingBlock:LBExistingBlock With:LBAnotherBlock
Was it helpful?

Solution

If you have two Blocks, just call them. Further, Blocks are objects, and can be put into NSArrays. 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 IMPs, those are just function pointers -- they can be put into a C array, or wrapped in NSValues 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];
}

OTHER TIPS

There's nothing built in, but you can just create a block that simply executes a series of blocks by calling them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top