NSIndexSet“-indexAtIndex:”? [英] NSIndexSet "-indexAtIndex:"?

查看:153
本文介绍了NSIndexSet“-indexAtIndex:”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这感觉像一个愚蠢的问题,因为它在我看来像我的用例必须是很常见的。

This feels like a dumb question because it seems to me like my use case must be quite common.

说我想代表一个稀疏的索引集NSIndexSet(这当然是它的)。我可以使用 -firstIndex 获得最低的一个和 -lastIndex 最高的,但什么是规范的方式一个单一的,任意的索引在中间,给定它的索引?文档让我不清楚。

Say I want to represent a sparse set of indexes with an NSIndexSet (which is of course what it's for). I can use -firstIndex to get the lowest one and -lastIndex for the highest, but what's the canonical way to get a single, arbitrary index in the middle, given its "index"? The docs have left me unclear.

例如。如果我有一个索引设置索引{0,5,8,10,12,28},我想说给我第四个索引,我希望回到10(或12我想关于我是否计数0,但让我们不要进入,你知道我的意思)。

E.g. if I have an index set with the indexes { 0, 5, 8, 10, 12, 28 }, and I want to say "give me the fourth index" and I'd expect to get back 10 (or 12 I suppose depending on whether I count the zeroth, but let's not get into that, you know what I mean).

注意,我不是在整个索引枚举组。在给定的时间点,我只是想知道集合中的第n个索引是按数字顺序。

Note that I'm not doing "enumeration" across the whole index set. At a given point in time I just want to know what the nth index in the set is by numerical order.

也许我的数据结构是错误的通常是为这种有序访问而设计的),但似乎没有NSIndexArray可以说。

Maybe my data structure is wrong ("set"s aren't usually designed for such ordered access), but there seems to be no NSIndexArray to speak of.

我缺少明显的东西?

谢谢!

推荐答案

我相信 NSIndexSet 使用范围存储其索引,因此不一定能快速返回 nth 索引。您可以枚举保持计数器,直到您的计数器达到您的目标索引:

I believe NSIndexSet stores its indexes using ranges, so there isn't necessarily a quick way to return the nth index. You could enumerate keeping a counter until your counter reaches your target index:

NSUInteger index = [indexSet firstIndex];

for (NSUInteger i = 0, target = 4; i < target; i++)
  index = [indexSet indexGreaterThanIndex:index];

这应该给你第四个索引。您甚至可以添加方法作为类别方法如果你想要:

That should give you the 4th index. You could even add the method as a category method if you want:

- (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;
}

但是,正如你所说,这可能不是最好的数据结构所以在使用这样的东西之前,请考虑更多。

But, as you said, this may not be the best data structure to use so do consider that more before going with something like this.

这篇关于NSIndexSet“-indexAtIndex:”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆