Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C For-In Loop Get Index

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?

like image 472
The Kraken Avatar asked Aug 25 '12 04:08

The Kraken


1 Answers

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);
       }];
like image 187
Tommy Avatar answered Nov 10 '22 03:11

Tommy