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

Gre*_*reg 38 objective-c

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

例如:

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

}
Run Code Online (Sandbox Code Playgroud)

小智 87

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

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

额外:在数组元素上并发执行块操作:

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


Rya*_*sal 45

我能想到的唯一方法是:

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

糟糕的方式

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

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

  • 不是第二个 - 既昂贵(搜索)又可能给出错误答案(数组中的同一个对象两次)......首先应该正常工作.@Greg:如果你想索引为什么不只是使用`for(NSUInteger ix = 0; ...`循环? (8认同)
  • 除了ObjC调度成本之外,你应该期望indexOfObject:比为自己增加变量花费更多,因为它是一个搜索.此外,Apple直接声明:"对于具有明确定义的顺序的集合或枚举器 - 例如NSArray或从数组派生的NSEnumerator实例 - 枚举按此顺序进行,因此简单地计算迭代会为您提供正确的索引.收集,如果你需要它." http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocFastEnumeration.html (6认同)
  • 作为更一般的情况,使用`NSUInteger`作为索引变量而不是`int`.你不知道数组中有多少项 - 以防万一.;) (2认同)