Enumeration

Enumeration is the process of sequentially operating on elements of an object—typically a collection—each at most once, one at a time in turn. Enumeration is also referred to as iteration. When you enumerate an object, you typically select one element within the object at a time and perform an operation on it or with it. The object is usually a collection such as an array or set. In the conceptually simplest case, you can use a standard C for loop to enumerate the contents of an array, as shown in the following example:

NSArray *array = // get an array;
NSInteger i, count = [array count];
for (i = 0; i < count; i++) {
    id element = [array objectAtIndex:i];
    /* code that acts on the element */
}

Using a for loop, however, can be inefficient, and requires an ordered collection of elements. Enumeration is more general. Cocoa therefore provides two additional means to enumerate objects—the NSEnumerator class and fast enumeration.

NSEnumerator

Several Cocoa classes, including the collection classes, can be asked to provide an enumerator so that you can retrieve elements held by an instance in turn. For example:

NSSet *aSet = // get a set;
NSEnumerator *enumerator = [aSet objectEnumerator];
id element;
 
while ((element = [enumerator nextObject])) {
    /* code that acts on the element */
}

In general, however, use of the NSEnumerator class is superseded by fast enumeration.

Fast Enumeration

Several Cocoa classes, including the collection classes, adopt the NSFastEnumeration protocol. You use it to retrieve elements held by an instance using a syntax similar to that of a standard C for loop, as illustrated in the following example:

NSArray *anArray = // get an array;
for (id element in anArray) {
    /* code that acts on the element */
}

As the name suggests, fast enumeration is more efficient than other forms of enumeration.

Prerequisite Articles

Related Articles