Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I get the array index within an "for (id item in items)" objective-c loop?

Tags:

objective-c

Alternatively, you can use -enumerateObjectsUsingBlock:, which passes both the array element and the corresponding index as arguments to the block:

[items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop)
{
    …
}];

Bonus: concurrent execution of the block operation on the array elements:

[items enumerateObjectsWithOptions:NSEnumerationConcurrent
    usingBlock:^(id item, NSUInteger idx, BOOL *stop)
{
    …
}];

Only way I can think of is:

NSUInteger count = 0;
for (id item in items)
{
    //do stuff using count as your index
    count++;
}

Bad Way

Alternatively, you can use the indexOfObject: message of a NSArray to get the index:

NSUInteger index;
for (id item in items)
{
    index = [items indexOfObject:item];
    //do stuff using index
}