【问题标题】:idiomatic way to enumerate NSArray by both index and element通过索引和元素枚举 NSArray 的惯用方法
【发布时间】:2014-11-26 00:07:51
【问题描述】:

我需要在iOS 中使用NSArray 执行类似于python 的enumerate() 函数的操作(我必须构建NSIndexPath 对象并检查该对象)。

我没有看到用于执行此类操作的内置方法(即没有 NSArray 等效于 NSDictionary 的 enumerateKeysAndObjectsUsingBlock: 方法)。这让我想到了两种通用的方法。

for (NSUInteger index = 0; index < mySequence.count; index++) {
    MyElementType *element = mySequence[index];
    //
    // code that works with both index and element
    //
}

NSUInteger index = 0;
for (MyElementType *element in mySequence) {
    //
    // code that works with both index and element
    //
    index++;
}

是否有充分的理由选择其他?或者有没有比这两种方法更好的第三种方法?

【问题讨论】:

  • 我不知道谁在投票,因为它没有显示任何研究。细读 NSArray 类参考资料会比写这个问题花费的时间更短。

标签: ios objective-c nsarray enumeration


【解决方案1】:

NSArray 中有以下 API:

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))

【讨论】:

  • 拍头。我被文档中的“任务”类别欺骗了。在 NSDictionary 中,Enumerating Dictionaries 下有一组方法。我没想到要查看Sending Messages to Elements。我认为这仅适用于 makeObjectsPerform... 方法系列。
猜你喜欢
  • 2020-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多