NSIndexSet "-indexAtIndex:"?
Asked Answered
R

4

15

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!

Recommendation answered 28/12, 2010 at 16:21 Comment(4)
Maybe you can work around this answer: https://mcmap.net/q/825155/-get-nsindexset-from-nsarrayDiploblastic
@Neilvert: I may end up doing so, but boxing the integers in NSNumbers seemed like overkill when a data structure to hold indexes seemed so convenient! :)Recommendation
Sets (including NSIndexSet) are unordered (or at least, their order is undefined). Therefore, indexAtIndex: doesn't make sense, because that's assuming an ordered set (which NSIndexSet is not).Inca
@Dave: In general I agree, although an index set is a bit special, as its contents are semantically orderable-- and NSIndexSet exposes firstIndex and lastIndex, which is a concession to that. (So is the implementation note that internally it stores ranges). So I don't feel like indexAtIndex: is as nonsensical as if I were asking about an NSSet.Recommendation
D
5

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.

Disappear answered 28/12, 2010 at 16:37 Comment(1)
Yup, sounds like I wasn't missing something obvious. Unfortunately, if it stores the indexes as ranges internally, it could expose indexAtIndex more efficiently than I can do it in a category, but point taken. Thanks.Recommendation
T
7

NSIndexSet isn't designed for that sort of access. Usually, you enumerate through the indexes in a set like so:

NSUInteger idx = [theSet indexGreaterThanOrEqualToIndex: 0];
while (idx != NSNotFound) {
    // idx equals the next index in the set.
    idx = [theSet indexGreaterThanIndex: idx];
}

@Richard points out this for loop is simpler:

for (NSUInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) {
    // i equals the next index in the set.
}

There's some block-based methods that are new to NSIndexSet as of Mac OS X 10.6/iOS 4.0, but I haven't reviewed them as of yet.

It should be trivial to modify the above example to keep a running count of indexes and stop when it reaches the fourth index in the set. ;)

Thimble answered 28/12, 2010 at 16:34 Comment(4)
that pretty much says it all, though I would have written the code sample as a for loop: for (NSUInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) {...}Refraction
That works too. :) Actually, that's cleaner than my sample. Stealing!Thimble
As a tip, if indexSet is nil, the for loop will loop infinitely because it reads: for (NSUInteger i = 0; i != NSNotFound; i = 0) { }Triangulation
@KyleRobson your objections holds equally for the while-loop construction.Refraction
D
5

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.

Disappear answered 28/12, 2010 at 16:37 Comment(1)
Yup, sounds like I wasn't missing something obvious. Unfortunately, if it stores the indexes as ranges internally, it could expose indexAtIndex more efficiently than I can do it in a category, but point taken. Thanks.Recommendation
R
3

Say I want to represent a sparse set of indexes with an NSIndexSet (which is of course what it's for).

[my emphasis]

Actually, no it's not. The documentation says this:

You should not use index sets to store an arbitrary collection of integer values because index sets store indexes as sorted ranges.

So if you are using it to store a sparse array of integers, it is quite inefficient. Also, the only way to get the nth index is to iterate from one end. You'd be better off using an array.

Regenerate answered 28/12, 2010 at 16:42 Comment(1)
Pshaw, semantics! If I only needed a known-contiguous set of indexes, I'd use an NSRange. :) There's value for me in the other methods on the class, but I also want this get-by-position behavior, though I grok that it ain't there.Recommendation
R
0

One more decision:

- (NSUInteger)indexAtIndex:(NSUInteger)index {
   __block NSUInteger result = NSNotFound;
   __block NSUInteger aCounter = 0;

   [self enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) {
      if (aCounter == index) {
         result = idx;
         *stop = YES;

      } else {
         aCounter++;
      }
   }];

   return result;
}
Rhynchocephalian answered 8/9, 2017 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.