Ben*_*tto 15 cocoa objective-c nsindexset
这感觉就像一个愚蠢的问题,因为在我看来,我的用例必须非常普遍.
假设我想用NSIndexSet表示一组稀疏索引(这当然是它的用途).我可以-firstIndex用来获得最低的和-lastIndex最高的,但是考虑到它的"索引",在中间获得单个任意索引的规范方法是什么?文档让我不清楚.
例如,如果我有一个索引设置索引{0,5,8,10,12,28},我想说"给我第四个索引",我希望得到10(或12我想取决于我是否计算第0个,但是我们没有考虑到这个,你知道我的意思).
请注意,我没有在整个索引集中进行"枚举".在给定的时间点,我只想通过数字顺序知道集合中的第n个索引是什么.
也许我的数据结构是错误的("set"通常不是为这种有序访问而设计的),但似乎没有NSIndexArray可以说.
我错过了一些明显的东西吗
谢谢!
NSIndexSet不是为那种访问而设计的.通常,您通过集合中的索引枚举如下:
NSUInteger idx = [theSet indexGreaterThanOrEqualToIndex: 0];
while (idx != NSNotFound) {
// idx equals the next index in the set.
idx = [theSet indexGreaterThanIndex: idx];
}
Run Code Online (Sandbox Code Playgroud)
@Richard指出这个for循环更简单:
for (NSUInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) {
// i equals the next index in the set.
}
Run Code Online (Sandbox Code Playgroud)
NSIndexSet从Mac OS X 10.6/iOS 4.0开始,有一些基于块的方法是新的,但我还没有回顾它们.
修改上面的示例以保持索引的运行计数并在到达集合中的第四个索引时停止应该是微不足道的.;)
我相信NSIndexSet使用范围存储其索引,因此不一定有返回nth索引的快速方法。您可以枚举一个计数器,直到计数器达到目标索引为止:
NSUInteger index = [indexSet firstIndex];
for (NSUInteger i = 0, target = 4; i < target; i++)
index = [indexSet indexGreaterThanIndex:index];
Run Code Online (Sandbox Code Playgroud)
那应该给你第四个索引。如果需要,您甚至可以将该方法添加为类别方法:
- (NSUInteger)indexAtIndex:(NSUInteger)anIndex
{
if (anIndex >= [self count])
return NSNotFound;
NSUInteger index = [indexSet firstIndex];
for (NSUInteger i = 0; i < anIndex; i++)
index = [self indexGreaterThanIndex:index];
return index;
}
Run Code Online (Sandbox Code Playgroud)
但是,正如您所说的那样,这可能不是最佳的数据结构,因此在进行此类操作之前,请考虑更多因素。