tags:

views:

128

answers:

3

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

+2  A: 

Maybe this will work?

if ( obj == [ someArray lastObject ] ) {
    // ...
}
codelogic
+4  A: 

You could use NSArray#lastObject to determine if obj is equal to [NSArray lastObject].

for (NSObject *obj in someArray) {
    if ([someArray lastObject] == obj) {
        NSLog(@"Last iteration");
    }
}
wfarr
+1  A: 

Rather than call into the array at every 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
    }
}
Abizern
You're still calling the method in the loop. I think you meant to swap the first two lines. Another tiny typo: uppercase 'F' in "For"
gclj5
Thanks for pointing that out - I'll edit it.
Abizern