40

How can I get the array index within a "for (id item in items)" loop in objective-c? For NSArray or NSMutableArray for example.

For example:

for (id item in items) {
    // How to get item's array index here

}
Greg
  • 34,042
  • 79
  • 253
  • 454
  • possible duplicate of [Keep track of index in fast enumeration](http://stackoverflow.com/questions/8113482/keep-track-of-index-in-fast-enumeration) – Pang Jul 05 '15 at 04:05

2 Answers2

88

Alternatively, you can use -enumerateObjectsUsingBlock:, which passes both the array element and the corresponding index as arguments to the block:

[items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop)
{
    …
}];

Bonus: concurrent execution of the block operation on the array elements:

[items enumerateObjectsWithOptions:NSEnumerationConcurrent
    usingBlock:^(id item, NSUInteger idx, BOOL *stop)
{
    …
}];
  • 1
    @Greg Just be aware [you need iOS 4 or later](http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html) to utilize blocks (not saying that is a huge negative - I actually kind of like this method :) ). – Ryan Wersal Apr 28 '11 at 01:13
  • Excelent answer. Very useful, well as efficient. Thanks! – Carlos Guzman Jan 31 '16 at 14:18
45

Only way I can think of is:

NSUInteger count = 0;
for (id item in items)
{
    //do stuff using count as your index
    count++;
}

Bad Way

Alternatively, you can use the indexOfObject: message of a NSArray to get the index:

NSUInteger index;
for (id item in items)
{
    index = [items indexOfObject:item];
    //do stuff using index
}
Ryan Wersal
  • 3,210
  • 1
  • 20
  • 29
  • 8
    Not the second - both costly (a search) and might give wrong answer (same object in array twice)... First should work fine. @Greg: If you want the index why not just use a `for(NSUInteger ix = 0;...` loop? – CRD Apr 28 '11 at 00:17
  • 6
    Above and beyond ObjC dispatch costs, you should expect indexOfObject: to cost a lot more than incrementing a variable for yourself because it's a search. Also, Apple directly state: "For collections or enumerators that have a well-defined order—such as an NSArray or an NSEnumerator instance derived from an array—the enumeration proceeds in that order, so simply counting iterations gives you the proper index into the collection if you need it." on http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocFastEnumeration.html – Tommy Apr 28 '11 at 00:18
  • 2
    As a more general case, use `NSUInteger` for an index variable instead of `int`. You don't know how many items are in the array - just in case. ;) – Itai Ferber Apr 28 '11 at 00:18
  • Good points from everyone, I will update it and add a giant disclaimer. :) – Ryan Wersal Apr 28 '11 at 00:26
  • @CRD - I just liked the syntax of "for (id item in items)" but was wondering if there was an easy/ok way to get the index – Greg Apr 28 '11 at 01:11