我最近一直在使用enumerateObjectsUsingBlock:
来满足我的快速枚举需求,而且我很难理解枚举块中BOOL *stop
的用法。
NSArray
类引用状态
stop
:对布尔值的引用。该块可以将值设置为YES
停止进一步处理数组。stop
参数是一个out-only 论点。您应该只将此布尔值设置为YES
块。
那么当然我可以在我的块中添加以下内容来停止枚举:
if (idx == [myArray indexOfObject:[myArray lastObject]]) {
*stop = YES;
}
根据我的判断,未明确将*stop
设置为YES
没有任何负面影响。枚举似乎在数组的末尾自动停止。那么在块中真的需要使用*stop
吗?
答案 0 :(得分:155)
Block的stop
参数允许您过早地停止枚举 。它等同于普通break
循环中的for
。如果要遍历数组中的每个对象,可以忽略它。
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;
}
}
}