How to increment an NSIndexPath

drekka picture drekka · Mar 9, 2012 · Viewed 7.3k times · Source

I have a data situation where I want to use an index path. As I'm traversing the data I want to increment the last node of an NSIndexPath. The code I have so far is:

int nbrIndex = [indexPath length];
NSUInteger *indexArray = (NSUInteger *)calloc(sizeof(NSUInteger),nbrIndex);
[indexPath getIndexes:indexArray];
indexArray[nbrIndex - 1]++;
[indexPath release];
indexPath = [[NSIndexPath alloc] initWithIndexes:indexArray length:nbrIndex];
free(indexArray);

This feels a bit, well, clunky - Is there a better way to do it?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Mar 9, 2012

You can try this - perhaps equally clunky, but at least a bit shorter:

NSInteger newLast = [indexPath indexAtPosition:indexPath.length-1]+1;
indexPath = [[indexPath indexPathByRemovingLastIndex] indexPathByAddingIndex:newLast];