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);
}];
Related videos on Youtube
Author by
The Kraken
Updated on November 22, 2020Comments
-
The Kraken over 3 years
Consider the following statement:
for (NSString *string in anArray) { NSLog(@"%@", string); }
How can I get the index of
string
inanArray
without using a traditionalfor
loop and without checking the value ofstring
with every object inanArray
? -
Joe Binney about 9 years
- indexOfObject
is anO(n)
operation, so this algorithm isO(n^2)
. It's strictly worse than incrementing an index on each iteration or using- enumerateObjectsUsingBlock:
, both of which are stillO(n)
. -
Pang about 7 yearsThis answer is wrong. If
anArray
contains duplicates, theindex
for the duplicated elements would be incorrect.