在快速枚举中跟踪索引

Shr*_*hri 28 cocoa-touch objective-c fast-enumeration

我想在使用快速枚举时得到当前对象的索引,即

for (MyClass *entry in savedArray) {
// What is the index of |entry| in |savedArray|?
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*l.s 65

查看NSArray的API ,您将看到该方法

- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))block
Run Code Online (Sandbox Code Playgroud)

所以试一试

[savedArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

    //... Do your usual stuff here

    obj  // This is the current object
    idx  // This is the index of the current object
    stop // Set this to true if you want to stop

}];
Run Code Online (Sandbox Code Playgroud)

  • 添加 - 通过调用`*stop = YES`来使用停止标志(只是`stop = YES`不起作用) (10认同)
  • 我想知道这是否更快,只需添加一个索引整数 (2认同)

Jos*_*sen 9

我认为最直接的解决方案是简单地手动增加索引.

NSUInteger indexInSavedArray = 0;
for (MyClass *entry in savedArray) {
   indexInSavedArray++;
 }
Run Code Online (Sandbox Code Playgroud)

或者,您可以不使用快速枚举.

    for (NSUInteger indexInSavedArray = 0; indexInSavedArray < savedArray.count; indexInSavedArray++) {
       [savedArray objectAtIndex:indexInSavedArray];
     }
Run Code Online (Sandbox Code Playgroud)

  • 是的,这会起作用,虽然效率非常低,因为它必须将isEqual发送到导致匹配对象的每个对象.例如,它将需要500个isEqual消息发送(并且如果对象实际上在isEqual中实际执行某些操作的计算)以获取第500个元素的索引,然后再发送501个消息以获取下一个对象.编辑:也许你是在讽刺,我错过了一个笑话:) (6认同)
  • 他也可以使用`[savedArray indexOfObject:entry];`:) (5认同)

Gra*_*ral 7

这个问题已经得到解答了,但我想我会补充说,计数迭代实际上是iOS Developer Library文档中提到的技术:

NSArray *array = <#Get an array#>;
NSUInteger index = 0;

for (id element in array) {
    NSLog(@"Element at index %u is: %@", index, element);
    index++;
}
Run Code Online (Sandbox Code Playgroud)

我确信会有一个奇特的伎俩,但我猜不是.:)

  • 简单示例:示例代码长度为2行.如果它长20行怎么办?在第5行,有人添加"继续"?继续将导致"元素"前进 - 但不是"索引".啊哈!所以你把index ++放在开头,就在使用它之后.但是如果有人然后尝试在循环体中引用它呢?现在它太大了......等等 (3认同)
  • @Adam虽然我同意你的观点,即Fast Enumeration设计得不是很好,你不能只使用`NSUInteger index = -1;`然后在开始时增加索引吗? (2认同)