Monday, June 17, 2013

NSIndexSet indexGreaterThanIndex example in Objective C (iOS).


NSIndexSet indexGreaterThanIndex

Returns either the closest index in the index set that is greater than a specific index or the not-found indicator.

- (NSUInteger)indexGreaterThanIndex:(NSUInteger)index

Parameters
index
Index being inquired about.

Return Value of [NSIndexSet indexGreaterThanIndex]
Closest index in the index set greater than index; NSNotFound when the index set contains no qualifying index.

NSIndexSet indexGreaterThanIndex example.
int indexIwantToFind = 2;
int valueAtThisIndex = [aSet firstIndex];
for(int i = 0; i < indexIwantToFind; i++){
    valueAtThisIndex = [aSet indexGreaterThanIndex:valueAtThisIndex];
}
NSLog(@"%d", valueAtThisIndex); //This will give you 39

Example of [NSIndexSet indexGreaterThanIndex].
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;
}

NSIndexSet indexGreaterThanIndex example.
/*int (as commented, unreliable across different platforms)*/
NSUInteger currentIndex = [someIndexSet firstIndex];
while (currentIndex != NSNotFound)
{
    //use the currentIndex

    //increment
    currentIndex = [someIndexSet indexGreaterThanIndex: currentIndex];
}

End of NSIndexSet indexGreaterThanIndex example article.