Take the 2-minute tour ×

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?

share|improve this question
add comment

3 Answers

up vote 6 down vote accepted

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.

share|improve this answer
I'd agree with this, but I believe it is "lastObject" not "lastElement". –  slycrel Dec 27 '10 at 22:33
Well now you and I agree! That's what I get for not checking the SDK docs for the call. –  Kendall Helmstetter Gelner Dec 27 '10 at 22:42
Great answer and just what I was looking for! –  Nic Hubbard Dec 27 '10 at 22:44
Not totally robust. As the same object can appear twice in the array, you could incorrectly do your "last thing" twice. Consider that problem when using this solution. Getting the array count before entering the loop and using an index is safer. –  Julien Dec 27 '10 at 23:06
That is a good point but generally you would have two distinct instances even if the objects equated to the same thing; but be aware that could be an issue in design. It's still safer from the standpoint of not getting a counter increment wrong in some way, as that is a lot more likely than putting two of the same object into an array. –  Kendall Helmstetter Gelner Dec 28 '10 at 0:41
show 2 more comments

Typically, fast enumeration means you are not using a counter...


The other form is without a counter is...

NSEnumerator *enumerator = [objectSet objectEnumerator];
id setObject;
while ((setObject = [enumerator nextObject]) != nil)
share|improve this answer
add comment

I don't believe there's any (simple) way of doing this - it's one of the trade-offs of using fast enumeration. As such, when you need to be aware of the index of the item you're enumerating over, you'll need to create an integer as you suggest.

That said, you'll still benefit from the fact that you can't go out of bounds when using a fast enumerator, etc.

share|improve this answer
add comment

Your Answer


