From Cocoa Core Competencies: 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.
In case you didn't know, id
is an Objective-C type that basically means “a pointer to any Objective-C object”. Note that the pointer-ness of id
is built in to it; you usually do not want to say id *
.
If you expect the elements of anArray
to be of a specific class, say MyObject
, you can use that instead:
for (MyObject *element in anArray) {
/* code that acts on the element */
}
However, neither the compiler nor the runtime will check that the elements are indeed instances of MyObject
. If an element of anArray
is not an instance of MyObject
, you'll probably end up trying to send it a message it doesn't understand, and get a selector-not-recognized exception.