Objective-C For-In Loop Get Index

22,338

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);
       }];
Share:
22,338

Related videos on Youtube

The Kraken
Author by

The Kraken

Updated on November 22, 2020

Comments

  • The Kraken
    The Kraken over 3 years

    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?

  • Joe Binney
    Joe Binney about 9 years
    - 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).
  • Pang
    Pang about 7 years
    This answer is wrong. If anArray contains duplicates, the index for the duplicated elements would be incorrect.