Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C: `continue` in collection enumeration block?

If I have an NSArray and I use enumerateUsingBlock to loop through elements in the array, but in some cases I need to skip the loop body and go to next element, is there any continue equivalent in block, or can I use continue directly?

Thanks!

update:

Just want to clarify, what I want to do is:

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

what I need is the continue equivalent in block.

like image 264
hzxu Avatar asked Nov 09 '12 06:11

hzxu


3 Answers

A block is a lot like an anonymous function. So you can use

return

to exit from the function with return type void.

like image 62
AntonPalich Avatar answered Nov 09 '22 01:11

AntonPalich


Use "continue" when using Fast Enumeration to do this.

Sample code:

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

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

    NSLog(@"%@",myThing);

}

and output:

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

Not a puppy in sight.

like image 28
Alex Zavatone Avatar answered Nov 08 '22 23:11

Alex Zavatone


You can not use continue in block, you will get error: continue statement not within a loop. use return;

[array enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        /* Do something with |obj|. */
        if (idx==1) {
            return;
    }
        NSLog(@"%@",obj);
    }];
like image 5
Parag Bafna Avatar answered Nov 09 '22 01:11

Parag Bafna