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])
Method 1: It is the naive method inside foreach loop to find iteration. Use a counter variable and check when the counter value is zero then it is the first iteration and when the counter value is length-1 then it is the last iteration.
To detect the last item in a list using a for loop: Use the enumerate function to get tuples of the index and the item. Use a for loop to iterate over the enumerate object. If the current index is equal to the list's length minus 1 , then it's the last item in the list.
Maybe this will work?
if ( obj == [ someArray lastObject ] ) {
// ...
}
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With