Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Control Flow and Functions

Loops and Fast Enumeration

Learn the for, while and do-while loops, break and continue, and the for-in fast enumeration syntax for arrays, dictionaries and sets, plus block-based enumeration.

Loops repeat work. Objective-C has the three C loops (for, while, do-while) and adds fast enumeration, a for ... in ... form that walks any collection safely and quickly. In everyday Cocoa code you will use for-in most often, and reserve counting loops for numeric work. This lesson covers each form, how to control a loop, and what to do when you need an index or must modify a collection.

The for loop

OBJECTIVEC
for (int i = 0; i < 5; i++) {
    NSLog(@"i = %d", i);
}

The three parts are initialization, condition (checked before each pass) and update. Any part can be empty; for (;;) loops forever until break.

For counts from an object, use NSUInteger and be careful with subtraction. NSUInteger is unsigned, so counting down with i >= 0 never ends:

OBJECTIVEC
for (NSUInteger i = array.count; i > 0; i--) {
    id item = array[i - 1];       // safe reverse loop
}

while and do-while

while tests first and may run zero times. do-while tests last and always runs once:

OBJECTIVEC
int n = 27;
while (n != 1) {
    n = (n % 2 == 0) ? n / 2 : 3 * n + 1;
}

int attempts = 0;
do {
    attempts++;
} while (![self tryConnect] && attempts < 3);

Use while when you do not know the number of passes beforehand, for example when reading input or draining a queue.

break and continue

break leaves the nearest loop. continue skips to the next pass:

OBJECTIVEC
for (int i = 1; i <= 10; i++) {
    if (i % 2 == 0) { continue; }   // skip evens
    if (i > 7) { break; }           // stop
    NSLog(@"%d", i);                // 1 3 5 7
}

Both affect only the innermost loop. To leave nested loops, use a flag or a return from a small helper method. Objective-C has goto, but it is rarely a good idea.

Fast enumeration

The for-in loop iterates over any object that supports it: NSArray, NSSet, NSDictionary (over keys), NSOrderedSet and others.

OBJECTIVEC
NSArray *names = @[@"Ada", @"Grace", @"Linus"];
for (NSString *name in names) {
    NSLog(@"Hello, %@", name);
}

NSDictionary *ages = @{ @"Ada": @36, @"Grace": @45 };
for (NSString *key in ages) {
    NSLog(@"%@ is %@", key, ages[key]);
}

It is shorter than an index loop, faster because the collection hands over many items per call, and safe: if the collection is mutated during enumeration, the runtime throws an exception instead of silently corrupting state.

OBJECTIVEC
NSMutableArray *list = [@[@1, @2, @3, @4] mutableCopy];
for (NSNumber *n in list) {
    if ([n intValue] % 2 == 0) {
        [list removeObject:n];      // crash: collection mutated while enumerating
    }
}

Safe alternatives are to loop over a copy (for (id x in [list copy])), to collect the items to remove and remove them afterwards, or to use removeObjectsAtIndexes: and predicates.

Dictionary key order is not defined. Sort the keys when order matters: for (NSString *key in [ages.allKeys sortedArrayUsingSelector:@selector(compare:)]).

You can declare the loop variable beforehand when you need it after the loop:

OBJECTIVEC
NSString *found = nil;
NSString *name;
for (name in names) {
    if ([name hasPrefix:@"G"]) { found = name; break; }
}

Needing the index

Fast enumeration does not give an index. Two common ways:

OBJECTIVEC
// 1. plain counting loop
for (NSUInteger i = 0; i < names.count; i++) {
    NSLog(@"%lu: %@", (unsigned long)i, names[i]);
}

// 2. block-based enumeration
[names enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL *stop) {
    NSLog(@"%lu: %@", (unsigned long)idx, name);
    if (idx == 1) { *stop = YES; }        // like break
}];

The block form lets you stop early by setting *stop = YES, and enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock: can run iterations in parallel. In a block, return acts like continue. Blocks are covered fully in their own chapter.

Use reverseObjectEnumerator to go backwards: for (id x in [array reverseObjectEnumerator]) { ... }.

Choosing a loop

Situation Loop
Fixed numeric range for
Visit every element of a collection for-in
Need the index and the object enumerateObjectsUsingBlock: or for
Repeat until a condition changes while
Run once, then repeat if needed do-while

Stand-in: numeric loops and control

C Stand-in (C): for, while, do-while, break and continue

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: how fast enumeration is shaped

Fast enumeration asks the collection for items in batches. This C model has a collection with a "next" function, and a loop that visits every element without knowing how the collection stores its data. It also shows why mutating during iteration is detected: a "mutation counter" is compared on each step.

C Stand-in (C): enumerating with a mutation guard

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Removing from a collection inside a for-in.
  • Counting down with an unsigned index and a condition i >= 0.
  • Using NSInteger i < array.count, a signed/unsigned comparison.
  • Using the loop variable's type wrongly (for (NSNumber *n in names)) so messages crash later.
  • Relying on dictionary key order.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does for (id x in collection) iterate over for an NSDictionary?

    Fast enumeration of a dictionary yields keys. Look up values with dict[key].
  2. 2. What happens if you remove an element from an NSMutableArray inside a for-in loop over it?

    Fast enumeration detects mutation and throws an exception.
  3. 3. How do you stop enumerateObjectsUsingBlock: early?

    The block receives a BOOL pointer. Setting it to YES ends the enumeration.
  4. 4. Which loop always executes its body at least once?

    do-while tests its condition after the body.

Summary

  • for, while and do-while work exactly as in C.
  • for (Type *x in collection) is the idiomatic way to visit each element.
  • Never mutate a collection while enumerating it; use a copy or collect changes first.
  • For the index, use a counting loop or enumerateObjectsUsingBlock:, where *stop = YES is the equivalent of break.
  • Beware unsigned counters when counting down.

Next: Functions