iphoneobjective-cfor-loopfast-enumeration

Objective C: Last object when using Fast Enumeration?


What is the best way to know when I have reached the last object in an array when using fast enumeration? Is there a better way than incrementing an int and then comparing that to the length of the array?


Solution

  • If you are starting with an array get out the last element (there's a specific call for that) and compare each element you get in the enumerator against that. Something like:

    id lastEl = [myArray lastObject];
    
    for ( id anEl in myArray )
    {
       if ( anEl == lastEl )
         .....  // do the last thing
    }
    

    The comparison cost is the same as with the counter, but then you don't have the cost of incrementing the counter or mistakes that invariably arise when you forget to increment the counter.