objective-ccocoansindexset

NSIndexSet "-indexAtIndex:"?


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 (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.

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).

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.

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.

Am I missing something obvious?

Thanks!


Solution

  • 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.