26

Consider the following statement:

for (NSString *string in anArray) {

    NSLog(@"%@", string);
}

How can I get the index of string in anArray without using a traditional for loop and without checking the value of string with every object in anArray?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
The Kraken
  • 3,158
  • 5
  • 30
  • 67

2 Answers2

57

Arrays are guaranteed to iterate in object order. So:

NSUInteger index = 0;
for(NSString *string in anArray)
{
    NSLog(@"%@ is at index %d", string, index);

    index++;
}

Alternatively, use the block enumerator:

[anArray
    enumerateObjectsUsingBlock:
       ^(NSString *string, NSUInteger index, BOOL *stop)
       {
           NSLog(@"%@ is at index %d", string, index);
       }];
Tommy
  • 99,986
  • 12
  • 185
  • 204
-6

Try this.

for (NSString *string in anArray)
{
  NSUInteger index = [anArray indexOfObject:string];
}
Sushil Sharma
  • 2,321
  • 3
  • 29
  • 49
muskat507
  • 21
  • 3
  • 9
    `- indexOfObject` is an `O(n)` operation, so this algorithm is `O(n^2)`. It's strictly worse than incrementing an index on each iteration or using `- enumerateObjectsUsingBlock:`, both of which are still `O(n)`. – Joe Binney Jan 29 '15 at 21:14
  • 8
    This answer is **wrong**. If `anArray` contains duplicates, the `index` for the duplicated elements would be incorrect. – Pang Mar 22 '17 at 07:52