打破嵌套块Objective-C

时间:2015-02-13 18:41:45

标签: objective-c block

如果我在块内的块内部有块等,那么我将如何“停止”执行任何进一步的块。

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

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

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

1 个答案:

答案 0 :(得分:3)

如果你想终止块本身的执行,你可以简单地从块返回,如下所示:

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