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])
views:
128answers:
3
+2
A:
Maybe this will work?
if ( obj == [ someArray lastObject ] ) {
// ...
}
codelogic
2009-02-14 06:51:04
+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
2009-02-14 06:52:05
+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
2009-02-14 11:03:58
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
2009-02-14 11:24:32
Thanks for pointing that out - I'll edit it.
Abizern
2009-02-14 18:17:13