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.
A block is a lot like an anonymous function. So you can use
return
to exit from the function with return type void.
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.
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);
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With