如何在“for(项目中的id项目)”objective-c循环中获取数组索引?

时间:2021-08-31 22:29:17

How can I get the array index within a "for (id item in items)" loop in objective-c? For NSArray or NSMutableArray for example.

如何在objective-c中的“for(id item in items)”循环中获取数组索引?例如,对于NSArray或NSMutableArray。

For example:

例如:

for (id item in items) {
    // How to get item's array index here

}

2 个解决方案

#1


42  

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:

或者,您可以使用NSArray的indexOfObject:消息来获取索引:

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

#2


85  

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

或者,您可以使用-enumerateObjectsUsingBlock :,它将数组元素和相应的索引作为参数传递给块:

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

#1


42  

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:

或者,您可以使用NSArray的indexOfObject:消息来获取索引:

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

#2


85  

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

或者,您可以使用-enumerateObjectsUsingBlock :,它将数组元素和相应的索引作为参数传递给块:

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