Objective-C For-In Loop Get Index

The Kraken picture The Kraken · Aug 25, 2012 · Viewed 20.5k times · Source

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?

Answer

Tommy picture Tommy · Aug 25, 2012

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