【问题标题】:Objective-C: `continue` in collection enumeration block?Objective-C:集合枚举块中的“继续”?
【发布时间】:2012-10-29 11:55:48
【问题描述】:

如果我有一个 NSArray 并且我使用 enumerateUsingBlock 循环遍历数组中的元素,但在某些情况下我需要跳过循环体并转到下一个元素,块中是否有任何 continue 等效项,或者我可以直接使用continue吗?

谢谢!

更新:

只是想澄清一下,我想做的是:

for (int i = 0 ; i < 10 ; i++)
{
    if (i == 5)
    {
        continue;
    }
    // do something with i
}

我需要的是块中的 continue 等效项。

【问题讨论】:

    标签: objective-c ios nsarray objective-c-blocks


    【解决方案1】:

    块很像一个匿名函数。所以你可以使用

    返回

    退出返回类型为 void 的函数。

    【讨论】:

    • 您好,请查看我的更新以了解我的意思,抱歉造成误解。
    • 好的,但return 不等于标准循环中的break 吗?如果是这样,那么continue 的等价物是什么? break 让我完全脱离循环,而 continue 跳转到下一个迭代。你如何在枚举块中做到这一点?
    • return without *stop = YES 相当于 for 循环中的 continuereturn with *stop = YES 等价于break
    【解决方案2】:

    你不能在块中使用 continue,你会得到error: continue statement not within a loop。使用返回;

    [array enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
            /* Do something with |obj|. */
            if (idx==1) {
                return;
        }
            NSLog(@"%@",obj);
        }];
    

    【讨论】:

      【解决方案3】:

      使用快速枚举执行此操作时,请使用“继续”。

      示例代码:

      NSArray *myStuff = [[NSArray alloc]initWithObjects:@"A", @"B",@"Puppies", @"C", @"D", nil];
      
      for (NSString *myThing in myStuff) {
          if ([myThing isEqualToString:@"Puppies"]) {
              continue;
          }
      
          NSLog(@"%@",myThing);
      
      }
      

      和输出:

      2015-05-14 12:19:10.422 test[6083:207] A
      2015-05-14 12:19:10.423 test[6083:207] B
      2015-05-14 12:19:10.423 test[6083:207] C
      2015-05-14 12:19:10.424 test[6083:207] D
      

      看不到小狗。

      【讨论】:

        猜你喜欢
        • 2020-03-27
        • 2011-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-14
        • 1970-01-01
        相关资源
        最近更新 更多