NSIndexSet firstIndex
- (NSUInteger)firstIndex
Return Value of [NSIndexSet firstIndex]
First index in the index set or NSNotFound when the index set is empty.
NSIndexSet firstIndex example.
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;
}
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;
}
Example of [NSIndexSet firstIndex].
- (void) goThroughIndexSet:(NSIndexSet *) anIndexSet
{
NSUInteger idx = [anIndexSet firstIndex];
while (idx != NSNotFound)
{
// do work with "idx"
NSLog (@"The current index is %u", idx);
// get the next index in the set
idx = [anIndexSet indexGreaterThanIndex:idx];
}
// all done
}
{
NSUInteger idx = [anIndexSet firstIndex];
while (idx != NSNotFound)
{
// do work with "idx"
NSLog (@"The current index is %u", idx);
// get the next index in the set
idx = [anIndexSet indexGreaterThanIndex:idx];
}
// all done
}
NSIndexSet firstIndex 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
int valueAtThisIndex = [aSet firstIndex];
for(int i = 0; i < indexIwantToFind; i++){
valueAtThisIndex = [aSet indexGreaterThanIndex:valueAtThisIndex];
}
NSLog(@"%d", valueAtThisIndex); //This will give you 39