什么是 bool *stop 参数 enumerateObjectsUsingBlock: 用于



我最近一直在使用enumerateObjectsUsingBlock:来满足我的快速枚举需求,我很难理解枚举块中BOOL *stop的用法。

NSArray类引用状态

stop:对布尔值的引用。块可以将值设置为 YES 停止对阵列的进一步处理。stop论点是唯一的 论点。您只应将此布尔值设置为 YES 块。

因此,我当然可以在我的块中添加以下内容以停止枚举:

if (idx == [myArray indexOfObject:[myArray lastObject]]) {
    *stop = YES;
}

据我所知,没有明确地将*stop设置为YES没有任何负面的副作用。枚举似乎在数组末尾自动停止。那么在块中使用*stop真的有必要吗?

块的stop参数允许您过早停止枚举。这相当于正常for循环的break。如果要遍历数组中的每个对象,可以忽略它。

for( id obj in arr ){
    if( [obj isContagious] ){
        break;    // Stop enumerating
    }
    if( ![obj isKindOfClass:[Perefrigia class]] ){
        continue;    // Skip this object
    }
    [obj immanetizeTheEschaton];
}

[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if( [obj isContagious] ){
        *stop = YES;    // Stop enumerating
        return;
    }
    if( ![obj isKindOfClass:[Perefrigia class]] ){
        return;    // Skip this object
    }
    [obj immanentizeTheEschaton];
}];

这是一个 out 参数,因为它是对调用作用域中变量的引用。它需要在 Block 中设置,但在 enumerateObjectsUsingBlock: 内部读取,就像通常从框架调用传递回代码NSError一样。

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block {
    // N.B: This is probably not how this method is actually implemented!
    // It is just to demonstrate how the out parameter operates!
    NSUInteger idx = 0;
    for( id obj in self ){
        BOOL stop = NO;
        block(obj, idx++, &stop);
        if( stop ){
            break;
        }
    }
}

最新更新