Yearly Archives: 2017

How to break a for loop in Objective C

Did you know that we can break out of a for loop before it finishes? It’s true – and it works with both regular for loops, as well as fast enumeration (for…in loops). And we can do it in either of two ways.

Let’s imagine we have an array with one thousand words. We’re only interested in finding a single one, and at that point we want to stop the loop.

Breaking with the break statement

The break statement will get us out of a for loop and continue programme execution after the finishing bracket of the loop. Here’s an example with a regular for loop:

    for (int i=0; i<1000; i++) {

        NSString *word = [array objectAtIndex:i];
        if ([word isEqualToString:@"one"]) {

            // break the loop
            break;
        }
    }
    // execution continues here
    NSLog(@"We've broken from the loop.");

The break statement also works with fast enumeration:

    for (NSString *word in array) {

        if ([word isEqualToString:@"up"] || [word isEqualToString:@"the"]) {

            // break the loop
            break;
        }
    }

    // execution continues here
    NSLog(@"We've broken from the loop.");

Breaking with “goto label”

Goto sounds like an old BASIC command – and we can still use it in Objective C. It doesn’t work on its own though and needs an arbitrary label to which we can direct the loop after we’ve broken from it.

Here’s how we might do this with a regular for loop:

    for (int i=0; i<1000; i++) {

        NSString *word = [array objectAtIndex:i];

        if ([word isEqualToString:@"the"]) {

            // break the loop with a label
            goto myLabel;
        }
    }

    myLabel:;
    NSLog(@"We've broken from the loop.");

Notice that when we declare the label where we’d like the programme to continue, we must do so with a colon (and a semi colon to finish the line).

The same principle also works with fast enumeration:

    for (NSString *word in array) {

        if ([word isEqualToString:@"up"] || [word isEqualToString:@"the"]) {

            // break the loop
            goto outer;
        } 
    }

    myLabel:;
    NSLog(@"We've broken the loop.");