【问题标题】:Iterating Through NSIndexSet遍历 NSIndexSet
【发布时间】:2015-05-12 22:13:07
【问题描述】:

如果你有一个名为 anArray 的 NSArray 对象和一个名为 anIndexSet 的 NSIndexSet 对象,你可以向前迭代一个索引集,如下所示。

摘录,Apple Documents

NSArray *anArray = [NSArray array];
NSIndexSet *anIndexSet = [NSIndexSet indexSetWithIndex:3];
NSUInteger index = [anIndexSet firstIndex];

while(index != NSNotFound) {
      NSLog(@" %@",[anArray objectAtIndex:index]);
      index = [anIndexSet indexGreaterThanIndex:index];
}

为什么要在上述场景中终止 NSRangeException?

【问题讨论】:

  • 因为你的数组是空的。索引 3 处没有对象。
  • 按如下方式启动 anArray 时出现同样的错误! NSArray *anArray = [NSArray arrayWithObject:anIndexSet];
  • 当然因为这只会将一个对象添加到数组中。所以索引 3 处仍然没有任何内容。要访问索引 3,您至少需要数组中的四个对象。
  • 其实我认为是while()条件的问题。 arrayWithObject:如果索引超出数组的末尾,则会引发 NSRangeException。同样创建与集合相同数量的数组也会产生相同的错误!
  • 您似乎对数组感到困惑。您需要实际将对象添加到数组中。然后,您的索引集应该引用对数组中的对象数量实际有效的索引。仅将索引设置为数组中唯一的对象来创建数组根本不是您想要做的。

标签: ios objective-c cocoa


【解决方案1】:

我认为这个例子更好地描述了这种情况。另外,没有像你说的那样使用空数组。非常感谢rmaddy!!!

NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:@"K",@"G",@"G",@"E",@"R",@"G",@"E",@"G",@"G",@"M", nil];

NSIndexSet *anIndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [mutableArray count])];

NSUInteger index = [anIndexSet lastIndex];

while (index != NSNotFound) {
    if ([[mutableArray objectAtIndex:index] isEqualToString:@"G"]) {
        [mutableArray removeObjectAtIndex:index];
    }
    index = [anIndexSet indexLessThanIndex:index];
}
NSLog(@" %@", mutableArray);

【讨论】:

  • 为什么要使用索引集来简单地遍历这样的数组对象?这是完全没有必要的。只需使用一个简单的for 循环。在这种情况下不需要NSIndexSet。甚至更好。去掉除数组之外的所有代码并添加一行:[mutableArray removeObject:@"G"];。这将从数组中删除所有 @"G" 值。不需要索引集或任何循环。
  • 在这种情况下是不必要的,但我的首要任务是了解索引集的工作。你认为我做错了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多