< Previous PageNext Page > Hide TOC

Enumerators: Traversing a Collection’s Elements

NSEnumerator is a simple abstract class whose subclasses enumerate collections of other objects. Collection objects—such as arrays, sets, and dictionaries—provide special NSEnumerator objects with which to enumerate their contents. You send nextObject repeatedly to a newly created NSEnumerator object to have it return the next object in the original collection. When the collection is exhausted, it returns nil. You can’t “reset” an enumerator after it’s exhausted its collection. To enumerate a collection again, you must create a new enumerator.

Note: On Mac OS X v10.5 and later it is more efficient to enumerate a collection using fast enumeration (see Fast Enumeration in The Objective-C 2.0 Programming Language).

Collection classes such as NSArray, NSSet, and NSDictionary include methods that return an enumerator appropriate to the type of collection. For instance, NSArray has two methods that return an NSEnumerator object: objectEnumerator and reverseObjectEnumerator. NSDictionary also has two methods that return an NSEnumerator object: keyEnumerator and objectEnumerator. These methods let you enumerate the contents of an NSDictionary by key or by value, respectively.

In Objective-C, an NSEnumerator retains the collection over which it’s enumerating (unless implemented differently by a custom subclass).

It is not safe to remove, replace, or add to a mutable collection’s elements while enumerating through it. If you need to modify a collection during enumeration, you can either: make a copy of the collection and enumerate using the copy; or, collect the information you require during the enumeration and apply the changes afterwards. The second pattern is illustrated in the following example.

NSMutableDictionary *myMutableDictionary = ... ;
NSMutableArray *keysToDeleteArray =
    [NSMutableArray arrayWithCapacity:[myMutableDictionary count]];
NSString *aKey;
NSEnumerator *keyEnumerator = [myMutableDictionary keyEnumerator];
while (aKey = [keyEnumerator nextObject])
{
    if ( /* test criteria for key or value */ ) {
        [keysToDeleteArray addObject:aKey];
    }
}
[myMutableDictionary removeObjectsForKeys:keysToDeleteArray];


< Previous PageNext Page > Hide TOC


© 2009 Apple Inc. All Rights Reserved. (Last updated: 2009-02-04)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.