打破嵌套块 Objective-C

Break out of nested blocks Objective-C

如果我在一个块中的一个块中有一个块,等等......我将如何"stop"执行任何进一步的块。

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

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

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

如果你想终止块本身的执行,你可以简单地从块中return,像这样:

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

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

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

如果块 C 已经 运行,并且你想让它知道它应该尽快退出,你可以这样做:

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