enumerateObjectsUsingBlock: 的 BOOL *stop 参数是什么? [英] What is the BOOL *stop argument for enumerateObjectsUsingBlock: used for?
问题描述
我最近一直在使用 enumerateObjectsUsingBlock:
来满足我的快速枚举需求,但我很难理解 BOOL *stop
在枚举块.
I've been using enumerateObjectsUsingBlock:
a lot lately for my fast-enumeration needs, and I'm having a hard time understanding the usage of BOOL *stop
in the enumeration block.
NSArray
类引用状态
stop
:对布尔值的引用.该块可以将值设置为 YES
以停止对数组的进一步处理.stop
参数是一个 out-only争论.您应该只在阻止.
stop
: A reference to a Boolean value. The block can set the value toYES
to stop further processing of the array. Thestop
argument is an out-only argument. You should only ever set this Boolean toYES
within the Block.
所以当然我可以在我的块中添加以下内容来停止枚举:
So then of course I can add the following in my block to stop the enumeration:
if (idx == [myArray indexOfObject:[myArray lastObject]]) {
*stop = YES;
}
据我所知,不将 *stop
明确设置为 YES
不会产生任何负面影响.枚举似乎在数组末尾自动停止.那么在块中使用 *stop
真的有必要吗?
From what I've been able to tell, not explicitly setting *stop
to YES
doesn't have any negative side effects. The enumeration seems to automatically stop itself at the end of the array. So is using *stop
really necessary in a block?
推荐答案
Block 的 stop
参数允许您过早停止枚举.它相当于普通 for
循环中的 break
.如果你想遍历数组中的每个对象,你可以忽略它.
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];
}];
这是一个输出参数,因为它是对来自调用范围的变量的引用.它需要在您的 Block 内设置,但在 enumerateObjectsUsingBlock:
内读取,与 NSError
通常从框架调用传递回您的代码的方式相同.
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 NSError
s 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;
}
}
}
这篇关于enumerateObjectsUsingBlock: 的 BOOL *stop 参数是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!