Saturday, August 30, 2008

Using Fast Enumeration

Using Fast Enumeration
The following code example illustrates using fast enumeration with NSArray and NSDictionary objects.

NSArray *array = [NSArray arrayWithObjects:

        @"One", @"Two", @"Three", @"Four", nil];

for (NSString *element in array) {

    NSLog(@"element: %@", element);

}

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:

    @"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil];

NSString *key;

for (key in dictionary) {

    NSLog(@"English: %@, Latin: %@", key, [dictionary valueForKey:key]);

}

You can also use NSEnumerator objects with fast enumeration, as illustrated in the following example:

NSArray *array = [NSArray arrayWithObjects:

        @"One", @"Two", @"Three", @"Four", nil];

NSEnumerator *enumerator = [array reverseObjectEnumerator];

for (NSString *element in enumerator) {

    if ([element isEqualToString:@"Three"]) {

        break;

    }

}


NSString *next = [enumerator nextObject];

// next = "Four"

For collections or enumerators that have a well-defined order—such as NSArray or NSEnumerator instance derived from an array—the enumeration proceeds in that order, so simply counting iterations will give you the proper index into the collection if you need it.
NSArray *array = /* assume this exists */;

NSInteger index = 0;

BOOL ok = NO;

for (id element in array) {

    if (/* some test for element */) {

        ok = YES;

        break;

    }

    index++;

}

if (ok) {

    NSLog(@"Test passed by element at index %d", index");

}