This post is describes techniques to enumerate your objects in a data collection, in this case an NSArray.

Using a typical for loop.

for (int i=0; i<=[myArray count]; i++){
id myObject = [myArray objectAtIndex:i];
// do something with the object
}

Using the NSEnumerator.

NSEnumerator * enum = [myArray objectEnumerator];
while (id myObject = [enum nextObject]){
// do something with the object
}

A much more concrete example can be found here.

Using Fast enumeration.

for (id myObject in myArray) {
// do something with the object
}

Using makeObjectsPerformSelector which is not considered as a different method but it could be very handy in some cases:

[newArray makeObjectsPerformSelector:@selector(doSomething)];

Which is equivalent to:

for (id myObject in myArray) {
[myObject performSelector:@selector(doSomething)];
}

Notes to take under consideration:

  • The id could be replaced with a type.
  • Enumerating mutable collection can raise exceptions
  • Fast enumeration is faster than the others, According to Apple “The enumeration is considerably more efficient than, for example, using NSEnumerator directly.” so is worth checking it out.
  • You can use this on your own collection classes by implementing the NSFastEnumeration protocol.
  • For makeObjectsPerformSelector read here for some insights

More information here