【问题标题】:Using enumerateObjectsAtIndexes or a for-loop to iterate through all indexes of an NSArray BEFORE a given index使用 enumerateObjectsAtIndexes 或 for 循环在给定索引之前遍历 NSArray 的所有索引
【发布时间】:2013-03-23 11:59:39
【问题描述】:

在给定索引之前迭代 NSArray 的索引的最简洁方法是什么?例如:

NSArray *myArray = @[ @"animal" , @"vegetable" , @"mineral" , @"piano" ];

[myArray enumerateObjectsAtIndexes:@"all before index 2" options:nil 
    usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
           // this block will be peformed on @"animal" and @"vegetable"
    }];

此外,如果给定索引为 0,则根本不应该循环。

最简洁、最优雅的方法是什么?到目前为止,我只拼凑了使用烦人的 NSRange 和索引集的笨拙的多行答案。有没有更好的方法可以忽略?

【问题讨论】:

  • 任意数量的实现方式。简洁并不意味着清晰。使用实际工作做得好的东西。不要与框架抗争。迭代 NSArray 不需要使用该方法。该方法提供了块使用,这对于块擅长的事情非常有用。

标签: objective-c nsarray iteration nsrange nsindexset


【解决方案1】:
NSArray *myArray = @[ @"animal" , @"vegetable" , @"mineral" , @"piano" ];
NSUInteger stopIndex = 2;

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (idx == stopIndex) {
        *stop = YES; // stop enumeration
    } else {
        // Do something ...
        NSLog(@"%@", obj);
    }
}];

【讨论】:

  • 这个不错。没有 if/else 有没有办法做到这一点?像 *stop = (idx == stopIndex) 之类的东西? (返回;):否;
  • @yourfriendzak:不是这样。根据文档,您应该只将YES 分配给*stop。从三元运算符中调用return 就是我所说的“混淆编程”:-)
  • 该要求是由于枚举方法的另一个变体提供的并发枚举。
【解决方案2】:
[myArray enumerateObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, idx)]     
                           options:0
                        usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

}];

【讨论】:

  • 为什么 -1NSMakeRange(-1, idx) 中?不应该是0 吗?
  • @yourfriendzak。还提供 nil 作为 (NSEnumerationOption) 选项的参数:会给你一个类型转换警告。因此,与其在这里给出 nil ,不如在您想忽略警告时提供 0 更好。
【解决方案3】:

怎么样:

index = 2;
for (int i = 0; i < [myArray count] && i < index; ++i) {
   id currObj = [myArray objectAtIndex:i];
   // Do your stuff on currObj;
} 

【讨论】:

  • 为什么需要i &lt; [myArray count]
  • 如果 index >= [myArray count] 你有麻烦了 :)
【解决方案4】:

我个人会使用Martin Ryourfriendzak 所示的基于块的枚举,giorashc 接受的答案可能是最糟糕的,因为它不提供突变保护。

我想添加一个(正确的)快速枚举示例

NSUInteger stopIndex = 2;
NSUInteger currentIndex = 0;
for (MyClass *obj in objArray) {
    if (currentIndex < stopIndex) {
        // do sth...
    } else {
        break;
    }
    ++currentIndex;      
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2012-09-02
    • 1970-01-01
    相关资源
    最近更新 更多