Next: 2.8 Searching for an Up: 2.7 Iterating over Array Previous: 2.7.1 First Way -

2.7.2 Second Way - Using objectEnumerator

There is another very important way to iterate over the elements of an array, and it is by using the -objectEnumerator method. This method returns an object of class NSEnumerator, which can be used to enumerate the objects in the array. The only real thing you need to know about NSEnumerator is that it has a method called -nextObject. The first time you invoke it, it returns the first object in the array. The second time you invoke it, it returns the second element on the array, and so on till there are no more objects in the array; at this point, the NSEnumerator returns nil. In the following example, the code to describe an array is rewritten in this second way:
void
describeArray (NSArray *array)
{
  NSEnumerator *enumerator;
  NSObject *obj;

  enumerator = [array objectEnumerator];

  while ((obj = [enumerator nextObject]) != nil)
    {
      NSLog (@"Next Object is: %@", obj);      
    }
  }
}
This second way is generally slightly faster than the first one but has a very important restriction: you should not modify the array (if it is a NSMutableArray) while enumerating its elements in this way. Be careful about this problem, because it is easy to forget this condition - this would introduce subtle bugs.


Next: 2.8 Searching for an Up: 2.7 Iterating over Array Previous: 2.7.1 First Way -
2008-01-16