【问题标题】:how can I get the array index within an "for (id item in items)" objective-c loop?如何在“for (id item in items)”objective-c 循环中获取数组索引?
【发布时间】:2023-03-18 00:23:01
【问题描述】:

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

例如:

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

}

【问题讨论】:

标签: objective-c


【解决方案1】:

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

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

奖励:对数组元素并发执行块操作:

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

【讨论】:

  • @Greg 请注意you need iOS 4 or later 使用块(并不是说这是一个巨大的负面影响——我实际上有点喜欢这种方法:))。
  • 优秀的答案。非常好用,效率也很高。谢谢!
【解决方案2】:

我能想到的唯一方法是:

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

不好的方式

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

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

【讨论】:

  • 不是第二个 - 既昂贵(搜索)并且可能给出错误答案(数组中的相同对象两次)...首先应该可以正常工作。 @Greg:如果你想要索引,为什么不直接使用for(NSUInteger ix = 0;... 循环?
  • 在 ObjC 调度成本之上,你应该期望 indexOfObject: 比为自己增加一个变量的成本要高得多,因为它是一个搜索。此外,Apple 还直接声明:“对于具有明确定义顺序的集合或枚举器(例如 NSArray 或从数组派生的 NSEnumerator 实例),枚举按该顺序进行,因此只需计算迭代次数即可为您提供正确的索引需要的话收藏。”在developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/…
  • 作为更一般的情况,使用NSUInteger 代替int 作为索引变量。您不知道数组中有多少项目 - 以防万一。 ;)
  • 大家好,我会更新它并添加一个巨大的免责声明。 :)
  • @CRD - 我只是喜欢“for (id item in items)”的语法,但想知道是否有一种简单/好的方法来获取索引
猜你喜欢
  • 2012-08-20
  • 1970-01-01
  • 1970-01-01
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-22
相关资源
最近更新 更多