NSIndexSet “-indexAtIndex:”?

后端 未结 4 1644
执念已碎
执念已碎 2020-12-18 20:57

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

Say I want to represent a sparse set of indexes with an NSIndexSet (whi

4条回答
  •  轮回少年
    2020-12-18 21:38

    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.

提交回复
热议问题