Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if I'm on the last iteration of a for X in Y loop in Objective-C

Tags:

objective-c

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])

like image 561
Sam Lee Avatar asked Feb 14 '09 06:02

Sam Lee


People also ask

How do you check for last iteration in foreach?

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.

How do I find the last iteration in Python?

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.


2 Answers

Maybe this will work?

if ( obj == [ someArray lastObject ] ) {
    // ...
}
like image 195
codelogic Avatar answered Sep 21 '22 09:09

codelogic


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");
    }
}
like image 31
wfarr Avatar answered Sep 22 '22 09:09

wfarr