Moshe
Moshe

Reputation: 58097

Detect the last element when using NSFastEnumeration?

Is it possible to detect the last item when using NSFastEnumeration?

for(NSString *str in someArray){

  //Can I detect if I'm up to the last string?

}

Upvotes: 1

Views: 307

Answers (3)

Nick Moore
Nick Moore

Reputation: 15857

I think the only way is the old fashioned way, something like:

    NSUInteger count = [someArray count];
    for (NSString *str in someArray) {
         if (--count==0) {
              //this is the last element
         }
    }

Upvotes: 2

bbum
bbum

Reputation: 162722

Is it possible to detect the last item when using NSFastEnumeration?

Not with 100% accuracy (or by limiting the array contents to being entirely unique pointers so that pointer comparison works as discussed in another question) without also doing a bunch of work that leads to just doing it the old way.

Note that if you can target 4.0+, you can use enumerateWithBlock: that gives both the item and the index. It is as fast or faster than fast enumeration, even.

Upvotes: 7

NSResponder
NSResponder

Reputation: 16861

At the end of the loop, "str" will still be pointing to the last element. What is it you need to do?

Upvotes: -1

Related Questions