Search code examples
objective-cblock

Break out of nested blocks Objective-C


If I have a block inside a block inside a block, etc... how would I "stop" executing any further blocks.

void (^simpleBlock)(void) = ^{
    //block A
    void (^simpleBlock)(void) = ^{
        //block B

        //something happened, stop block C from executing...

        void (^simpleBlock)(void) = ^{
            //block C
        };
    };
};

Solution

  • If you want to terminate the execution of the block itself, you can simply return from the block, like this:

    void (^simpleBlock)(void) = ^{
        //block B
    
        //something happened, stop block C from executing...
        return;
    
        void (^simpleBlock)(void) = ^{
            //block C
        };
    };
    

    If block C is running already, and you wish to let it know that it should quit as soon as possible, you can do this:

    // Set up a flag that is shared among all blocks
    __block BOOL blockCShouldStop = NO;
    void (^simpleBlock)(void) = ^{
        //block A
        void (^simpleBlock)(void) = ^{
            //block B
    
            //something happened, stop block C from executing...
            blockCShouldStop = YES; // <<== Set the flag
            return;
    
            void (^simpleBlock)(void) = ^{
                //block C
                ...
                if (blockCShouldStop) { // <<== Check the flag
                    return;
                }
            };
        };
    };