How to find out if I am at the last iteration for loop X to Y in Objective-C

I have a loop using the syntax for (NSObject * obj in someArray) {}. Is there an easy way to tell if I'm at the last iteration of the loop (ie Without using [someArray count])

+6
objective-c
source share
3 answers

Maybe this will work?

if ( obj == [ someArray lastObject ] ) { // ... } 
+15
source share

You can use NSArray#lastObject to determine if obj [NSArray lastObject] .

 for (NSObject *obj in someArray) { if ([someArray lastObject] == obj) { NSLog(@"Last iteration"); } } 
+14
source share

Instead of being called into an array at each iteration, it might be better to cache the last object in the array:

 NSObject *lastObject = [someArray lastObject]; for (NSObject *obj in someArray) { // Loop code if (obj == lastObject) { // do what you want for the last array item } } 
+5
source share

All Articles