Question

How would you stop fast enumeration once you have gotten what your looking for.

In a for loop I know you just set the counter number to like a thousand or something. Example:

for (int i=0;i<10;i++){
    if (random requirement){
        random code
        i=1000;
    }
}

so without converting the fast enumeration into a forward loop type thing (by comparing i to the [array count] how can you stop a fast enumeration in the process?

Was it helpful?

Solution

from the docs

for (NSString *element in array) {
    if ([element isEqualToString:@"three"]) {
        break;
    }
}

if you want to end enumeration when a certain index is reached, block-based enumeration might be better, as it give you the index while enumerating:

[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    //…
    if(idx == 1000) 
        *stop = YES;
}];

OTHER TIPS

for (id object in collection) {
  if (condition_met) {
    break;
  }
}

Couldn't you just use a break statement?

for (int x in /*your array*/){
    if (random requirement){

        random code
        break;
    }
}

Just adding that for nested loops, a break on an inner loop breaks just that loop. Outer loops will continue. If you want to break out completely you could do so like this:

BOOL flag = NO;
for (NSArray *array in arrayOfArrays) {
    for (Thing *thing in array) {
        if (someCondition) {
            // maybe do something here
            flag = YES;
            break;
        }
    }
    if (flag) {
        break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top