NSArray *names = [NSArray arrayWithObjects:@"Ann", @"Bob", @"Cate", nil];
NSDictionary *ages = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:31], @"Ann",
[NSNumber numberWithInt:27], @"Bob", nil];
// *** before: ***
// either an index loop, which fits an array only
for (NSUInteger i = 0; i < [names count]; i++) {
NSString *name = [names objectAtIndex:i];
NSLog(@"%@", name);
}
// or an enumerator, which was the only way over a dictionary or a set
NSEnumerator *enumerator = [ages keyEnumerator];
id key;
while ((key = [enumerator nextObject]) != nil) {
NSLog(@"%@ is %@", key, [ages objectForKey:key]);
}
// *** in version 2.0: ***
// one loop for every collection, and it is faster: the collection hands
// out its objects in batches instead of one message per step
for (NSString *name in names) {
NSLog(@"%@", name);
}
for (NSString *key in ages) { // a dictionary walks its keys
NSLog(@"%@ is %@", key, [ages objectForKey:key]);
}
for (NSString *name in [names reverseObjectEnumerator]) {
NSLog(@"%@", name);
}
// the collection must not be changed inside the loop: doing so throws
// NSGenericException instead of silently returning wrong objects