enumerateObjectsUsingBlock的BOOL * stop参数是什么? [英] What is the BOOL *stop argument for enumerateObjectsUsingBlock: used for?

查看:2319
本文介绍了enumerateObjectsUsingBlock的BOOL * stop参数是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用 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
参数。您只应在
块中将此布尔值设置为 YES

stop: A reference to a Boolean value. The block can set the value to YES to stop further processing of the array. The stop argument is an out-only argument. You should only ever set this Boolean to YES 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?

推荐答案

stop 阻止的参数允许您提前停止枚举 。这相当于 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];
}];

这是一个out参数,因为它需要在Block中设置, c $ c> enumerateObjectsUsingBlock:,同样的方式 NSError 通常从框架调用传递回你的代码。

That is an out parameter because it needs to be set inside your Block, but read inside of enumerateObjectsUsingBlock:, the same way NSError 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆