objective-cobjective-c-blocksimp

Constructing or composing my own blocks or imps


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

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];
    }