objective-cfor-loopfor-in-loopfast-enumeration

How do you stop fast enumeration?


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?


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;
    }];