NSIndexSet上的快速枚举

cfi*_*her 46 macos cocoa nsindexset

你能快速列举一下NSIndexSet吗?如果没有,枚举集合中项目的最佳方法是什么?

Bar*_*ark 145

在OS X 10.6+和iOS SDK 4.0+中,您可以使用以下-enumerateIndexesUsingBlock:消息:

NSIndexSet *idxSet = ...

[idxSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
  //... do something with idx
  // *stop = YES; to stop iteration early
}];
Run Code Online (Sandbox Code Playgroud)

  • 将NSInteger更改为NSUInteger (2认同)

Eva*_*ski 22

一个while循环应该可以解决问题.使用上一个索引后,它会递增索引.

/*int (as commented, unreliable across different platforms)*/
NSUInteger currentIndex = [someIndexSet firstIndex];
while (currentIndex != NSNotFound)
{
    //use the currentIndex

    //increment
    currentIndex = [someIndexSet indexGreaterThanIndex: currentIndex];
}
Run Code Online (Sandbox Code Playgroud)

  • 有效索引可以超出`int`可表示的值范围,因为索引是无符号的.此外,当定义64位平台或使用定义的"NS_BUILD_32_LIKE_64"构建时,索引是64位值.使用`NSUInteger`代替`int`以匹配所有平台下由`NSIndexSet`存储的类型. (2认同)
  • @Jeremy W. Sherman:实际上索引实际上限于那些可以用**正**"NSInteger"表示的值,因为"未找到"的返回值是`NSNotFound`,它与`NSIntegerMax`相同 (2认同)

Pet*_*sey 20

快速枚举必须产生对象; 由于NSIndexSet包含标量数字NSUInteger,而不包含对象,因此,您无法快速枚举索引集.

假设它可以将它们装入NSNumbers,但那时它不会很快.


Dav*_*ong 10

简答:不. NSIndexSet不符合<NSFastEnumeration>协议.