Thursday, March 31, 2011

How to tell if I'm on the last iteration of a for X in Y loop in 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])

From stackoverflow
  • 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");
        }
    }
    
  • 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
        }
    }
    
    gclj5 : 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"
    Abizern : Thanks for pointing that out - I'll edit it.

0 comments:

Post a Comment