枚举对象的 BOOL * stop 参数是什么?

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

NSArray类引用状态

stop: 对布尔值的引用。该块可以将该值设置为 YES 停止对数组的进一步处理 参数中将此布尔值设置为 YES 路霸。

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

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

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

35358 次浏览

The stop argument to the Block allows you to stop the enumeration prematurely. It's the equivalent of break from a normal for loop. You can ignore it if you want to go through every object in the array.

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

That is an out parameter because it is a reference to a variable from the calling scope. It needs to be set inside your Block, but read inside of enumerateObjectsUsingBlock:, the same way NSErrors are commonly passed back to your code from framework calls.

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