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