7

我想在我的课堂上制作一个方法,就像enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)NSDictionary课堂上一样。

我对块的使用有一点了解,但我无法弄清楚如何使enumerateObjectsUsingBlock函数使用的停止条件。有什么建议么?

4

2 回答 2

14

stop标志的使用方式如下:

[coll enumerateUsingBlock:^(id o, NSUInteger i, BOOL *stop) {
      if (... check for stop ... ) {
           *stop = YES;
           return;
      }
 }];

当枚举块返回时,集合检查*stop. 如果是YES,则停止枚举。

它以这种方式实现,而不是返回值,因为这允许并发枚举而不检查块的返回值(这会产生开销)。即在并发枚举中,集合可以进行dispatch_async()任意数量的同时迭代并定期检查*stop。每当*stop转换到 时YES,它就会停止调度更多的块(这也是stop标志不是硬停止的原因;一些未指定数量的迭代可能仍在进行中)。

在您的迭代器中,您可能会这样做:

 BOOL stop = NO;
 for(...) {
     enumerationBlock(someObj, someIndex, &stop);
     if (stop) break;
 }
于 2013-04-07T22:40:56.660 回答
6

以下代码定义了一个方法,该方法将块作为参数并一直执行它,直到shouldStop被块设置为NO

- (void)myMethod:(void(^)(BOOL *stop))aBlock {
    BOOL shouldStop = NO;
    while (!shouldStop) {
        aBlock(&shouldStop);
    }
}

The explanation is fairly simple. A block is a function that takes some parameters. In this case we pass as a parameter a pointer to a BOOL variable we own. By doing so we are allowing the block to set that variable and - in this case - indicate that the loop should stop.

At this point, the block passed could do something like

[self myMethod:^(BOOL *stop) {
      if (arc4random_uniform(1)) {
          *stop = YES;
      }
}];
于 2013-04-07T22:42:24.000 回答