TExcelTAD
Home › Objective-C › Fast & Block Enumeration

Fast & Block Enumeration

There are three ways to visit every element of a Foundation collection. In modern code you'll mostly use the first two.

Style Syntax Best for
fast enumeration for (id x in collection) the everyday loop: short and fast
block enumeration enumerateObjectsUsingBlock: when you also need the index (or key), or want to stop early
index loop for (NSUInteger i = 0; i < a.count; i++) stepping by more than one, walking two arrays together

Fast enumeration

for … in works with arrays, sets, dictionaries (it visits the keys) and any class that adopts NSFastEnumeration:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *cities = @[@"Oslo", @"Quito", @"Hanoi"];
        for (NSString *city in cities) {
            NSLog(@"city: %@", city);
        }

        NSDictionary *ages = @{@"Lea": @31};
        for (NSString *name in ages) {             // dictionaries give you keys
            NSLog(@"%@ is %@", name, ages[name]);
        }

        // Reverse order with an enumerator
        for (NSString *city in [cities reverseObjectEnumerator]) {
            NSLog(@"backwards: %@", city);
        }

        // break and continue work as usual
        for (NSString *city in cities) {
            if ([city hasPrefix:@"Q"]) {
                NSLog(@"found %@, stopping", city);
                break;
            }
        }
    }
    return 0;
}
city: Oslo
city: Quito
city: Hanoi
Lea is 31
backwards: Hanoi
backwards: Quito
backwards: Oslo
found Quito, stopping

The loop variable's type (NSString *) is a promise you make: the compiler doesn't check what's in the array. With lightweight generics (NSArray<NSString *> *) it can.

Block enumeration of arrays

enumerateObjectsUsingBlock: calls a block for every element, passing the object, its index and a stop pointer. Set *stop = YES to end early.

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *runners = @[@"Kim", @"Jo", @"Sam", @"Ali", @"Max"];

        [runners enumerateObjectsUsingBlock:^(NSString *name, NSUInteger idx, BOOL *stop) {
            NSLog(@"#%lu %@", (unsigned long)(idx + 1), name);
            if (idx == 2) {
                *stop = YES;          // only the podium
            }
        }];

        // Visit in reverse with an option
        [runners enumerateObjectsWithOptions:NSEnumerationReverse
                                  usingBlock:^(NSString *name, NSUInteger idx, BOOL *stop) {
            if (idx >= 3) {
                NSLog(@"from the back: %@", name);
            }
        }];
    }
    return 0;
}
#1 Kim
#2 Jo
#3 Sam
from the back: Max
from the back: Ali

Block enumeration of dictionaries

For dictionaries, enumerateKeysAndObjectsUsingBlock: hands you each key and its value, without a second lookup. The order is still unspecified, so this example collects results and sorts them before printing:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSDictionary *temps = @{@"Rome": @24, @"Oslo": @11, @"Cairo": @33, @"Lima": @19};
        NSMutableArray *warm = [NSMutableArray array];
        __block NSInteger sum = 0;     // __block lets the block modify this variable

        [temps enumerateKeysAndObjectsUsingBlock:^(id city, id t, BOOL *stop) {
            sum += [t integerValue];
            if ([t integerValue] >= 20) {
                [warm addObject:[NSString stringWithFormat:@"%@ (%@ C)", city, t]];
            }
        }];

        [warm sortUsingSelector:@selector(compare:)];
        NSLog(@"warm: %@", [warm componentsJoinedByString:@", "]);
        NSLog(@"average: %.2f C", (double)sum / temps.count);
    }
    return 0;
}
warm: Cairo (33 C), Rome (24 C)
average: 21.75 C

The block's key and value parameters are declared as id here. Apple's SDK also accepts NSString *city, NSNumber *t thanks to lightweight generics, but id works with every Foundation implementation.

__block is needed because blocks normally capture a copy of local variables. The Block Capture lesson explains it in detail. Adding to warm doesn't need it, because we only send messages to the array object, never reassign the variable.

Index loops and enumerators

The classic C loop is still useful, for instance to compare neighbours:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *prices = @[@100, @104, @101, @110];
        for (NSUInteger i = 1; i < prices.count; i++) {
            NSInteger change = [prices[i] integerValue] - [prices[i - 1] integerValue];
            NSLog(@"day %lu: %+ld", (unsigned long)i, (long)change);
        }

        // NSEnumerator: the pre-2006 style you'll still meet in old code
        NSEnumerator *e = [@[@"x", @"y"] objectEnumerator];
        id item;
        while ((item = [e nextObject])) {
            NSLog(@"enumerator gave %@", item);
        }
    }
    return 0;
}
day 1: +4
day 2: -3
day 3: +9
enumerator gave x
enumerator gave y

%+ld always prints the sign, which is nice for changes.

Choosing

Tip: Default to for … in. Reach for block enumeration when you need the index or key-value pairs, and for an index loop when the position itself drives the logic. In all three, don't mutate the collection you're iterating.

Test yourself

What does for (id x in dictionary) iterate over?

  1. The values
  2. The keys
  3. Key-value pairs
  4. Nothing: dictionaries can't be enumerated

How do you stop enumerateObjectsUsingBlock: early?

  1. return NO;
  2. break;
  3. *stop = YES;
  4. stop();

Why does the dictionary example declare __block NSInteger sum?

  1. To make it thread-safe
  2. So the block can modify the captured variable
  3. To store it on the heap permanently
  4. Because NSInteger needs it