Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
Nic Hubbard Avatar asked Dec 27 '10 22:12

Nic Hubbard


1 Answers

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.

like image 110
Kendall Helmstetter Gelner Avatar answered Sep 17 '22 12:09

Kendall Helmstetter Gelner