Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios break nested loop

Tags:

objective-c

If I have a while loop with a for loop inside of the while loop, how can I break both loops?

I'm doing this because the extra 250ms I get from not completing these loops after I found what I want adds up to be valuable after a while.

pseudocode:

while(alwaysTrue) {
    for(NSArray *arr in twoThousandItems) {
        if(IFoundWhatIWasLookingFor) {
            // assign some stuff here
            // break everything, not just the for loop.
        }
    }
}
like image 939
Jacksonkr Avatar asked Feb 23 '12 18:02

Jacksonkr


1 Answers

This is where goto is your friend. Yes, that goto.

while(alwaysTrue) {
    for(NSArray *arr in twoThousandItems) {
        if(IFoundWhatIWasLookingFor) {
            // assign some stuff here
            // break everything, not just the for loop.
            goto BAIL;
        }
    }
}
BAIL:
NSLog(@"Freedom!");

The other option is to have short circuits in your loops.

while(alwaysTrue && !found) {
    for(NSArray *arr in twoThousandItems) {
        if(IFoundWhatIWasLookingFor) {
            // assign some stuff here
            // break everything, not just the for loop.
            found = YES;
            break;
        }
    }
}
like image 96
Joshua Weinberg Avatar answered Oct 10 '22 13:10

Joshua Weinberg