Objective-C:集合枚举块中的`continue`?

hzx*_*zxu 42 objective-c nsarray ios objective-c-blocks

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

谢谢!

更新:

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

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

我需要的是continue块中的等价物.

Ant*_*ich 70

块很像匿名函数.所以你可以使用

返回

退出函数返回类型为void.

  • `return`*没有*`*stop = YES`相当于for循环中的`continue`.`return**with*`*stop = YES`相当于`break`. (15认同)
  • 对于你的意思,答案仍然是正确的. (4认同)
  • 好的,但是在标准循环中不是`return`相当于`break`吗?如果是这样,那么什么是"继续"?`break`完全打破了我的循环,而`continue`跳转到下一次迭代.你如何在枚举块中做到这一点? (3认同)

Ale*_*one 8

使用"快速枚举"时,请使用"继续"执行此操作.

示例代码:

NSArray *myStuff = [[NSArray alloc]initWithObjects:@"A", @"B",@"Puppies", @"C", @"D", nil];

for (NSString *myThing in myStuff) {
    if ([myThing isEqualToString:@"Puppies"]) {
        continue;
    }

    NSLog(@"%@",myThing);

}
Run Code Online (Sandbox Code Playgroud)

并输出:

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
Run Code Online (Sandbox Code Playgroud)

看来不是小狗.


Par*_*fna 5

您不能使用continue in block,您将得到 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);
    }];
Run Code Online (Sandbox Code Playgroud)