6

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?

drekka
  • 20,957
  • 14
  • 79
  • 135

4 Answers4

6

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];
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Nice. I like it better because it avoid all the fluffing around with c arrays. THanks for that. – drekka Mar 10 '12 at 02:28
5

One line less this way:

indexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:actualIndexPath.section];

Rob Caraway
  • 3,856
  • 3
  • 30
  • 37
  • This will work for table view index paths, but if I remember correctly I was considering a situation where the index path was for something else and longer than two nodes. – drekka Aug 10 '12 at 01:55
3

Check my solution on Swift:

func incrementIndexPath(indexPath: NSIndexPath) -> NSIndexPath? {
    var nextIndexPath: NSIndexPath?
    let rowCount = numberOfRowsInSection(indexPath.section)
    let nextRow = indexPath.row + 1
    let currentSection = indexPath.section

    if nextRow < rowCount {
        nextIndexPath = NSIndexPath(forRow: nextRow, inSection: currentSection)
    }
    else {
        let nextSection = currentSection + 1
        if nextSection < numberOfSections {
            nextIndexPath = NSIndexPath(forRow: 0, inSection: nextSection)
        }
    }

    return nextIndexPath
}
SoftDesigner
  • 5,640
  • 3
  • 58
  • 47
1

A for loop in Swift 4 achieving similar results with an embedded UITableView, iterating through the for loop, filling the detail text of a cell with "Row Updated"

for i in 0 ..< 9 {
     let nextRow = (indexPath?.row)! + i
     let currentSection = indexPath?.section
     let nextIndexPath = NSIndexPath(row: nextRow, section: currentSection!)

     embeddedViewController.tableView.cellForRow(at: nextIndexPath as IndexPath)?.detailTextLabel?.text = "Row Updated"

     let myTV = embeddedViewController.tableView
     myTV?.cellForRow(at: nextIndexPath as IndexPath)?.backgroundColor = UIColor.red
     myTV?.deselectRow(at: nextIndexPath as IndexPath, animated: true)                            
}
Will Buffington
  • 1,048
  • 11
  • 13