如何在Objective-C中打破块循环?

Alm*_*bek 4 iteration block objective-c break ios

我在头文件中有这些声明:
注意: 我不会解释整个代码,我认为这很容易理解

typedef void (^loopCell)(id cell);
-(id)allCells:(loopCell)cell;
Run Code Online (Sandbox Code Playgroud)

allCells功能实现:

-(id)allCells:(loopCell)cell
{
    for (AAFormSection *section in listSections)
    {
        for (id _cell in section.fields) {
            cell(_cell);
        }
    }
    return nil;
}
Run Code Online (Sandbox Code Playgroud)

allCells功能的用法:

-(void)setFieldValue:(NSString *)value withID:(int)rowID
{    
    [self allCells:^(id cell) {
        if([cell isKindOfClass:[AAFormField class]]) {
            AAFormField *_cell = (AAFormField *)cell;
            if(_cell.rowID == rowID) {
                _cell.value = value;
                //return; Here I want to terminate loop
            }
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,我不能在中间终止 allCells循环(实际上当我在循环中找到我需要的对象时,我不希望迭代通过其他对象)

如何在中间停止allCells循环?

rma*_*ddy 9

看看文档NSArray enumerateObjectsUsingBlock:.他们设置块签名以获取BOOL指针.将stop BOOL设置为YES以使迭代停止.

typedef void (^loopCell)(id cell, BOOL *stop);

-(id)allCells:(loopCell)cell {
    BOOL stop = NO;
    for (AAFormSection *section in listSections) {
        for (id _cell in section.fields) {
            cell(_cell, &stop);
            if (stop) {
                break;
            }
        }
        if (stop) {
            break;
        }
    }

    return nil;
}

-(void)setFieldValue:(NSString *)value withID:(int)rowID {    
    [self allCells:^(id cell, BOOL *stop) {
        if([cell isKindOfClass:[AAFormField class]]) {
            AAFormField *_cell = (AAFormField *)cell;
            if(_cell.rowID == rowID) {
                _cell.value = value;
                if (stop) {
                    *stop = YES;
                }
            }
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)