Some tableviews require users to be able to edit the cell’s row position. Easily done by enabling the -(void) tableView:(UITableView *)tableView commitEidtingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath delegate of UITableView.

But, keeping track of those changes, man, that was painful. Here’s my fix:
-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath {
Stocks *movedStok = [self.stocksArray objectAtIndex:sourceIndexPath.row];
Stocks *destStok = [self.stocksArray objectAtIndex:destinationIndexPath.row];
// if moved up in the tableView
if (destinationIndexPath.row < sourceIndexPath.row) {
movedStok.sequence = destinationIndexPath.row;
destStok.sequence = destinationIndexPath.row + 1;
for (NSInteger between = destinationIndexPath.row + 1; between < sourceIndexPath.row; between ++) { Stocks *affectedStok = [self.stocksArray objectAtIndex:between]; affectedStok.sequence = affectedStok.sequence + 1; } } // if moved down in the tableView if (destinationIndexPath.row > sourceIndexPath.row) {
movedStok.sequence = destinationIndexPath.row;
destStok.sequence = destinationIndexPath.row - 1;
for (NSInteger between = sourceIndexPath.row + 1; between < destinationIndexPath.row; between ++) {
Stocks *affectedStok = [self.stocksArray objectAtIndex:between];
affectedStok.sequence = affectedStok.sequence - 1;
}
}
[self saveContext]; // saves objects to CoreData
}

It did take a several hours to:

  • implement the sequence feature as a persistent store of tableView position.
  • I had to modify the CoreData model with a lightweight migration.
  • I had to change the navigationBar button “Edit” into “Done” and then back again as the user tapped “Edit” to start the move and then “Done” to finish it.
  • Then change the AddViewController so that the sequence would automatically add the object to the bottom of the tableView, and
  • then implement this method whenever the moveRoveAtIndexPath method is invoked.

Of course there were several dead ends that consumed time and effort, but nevertheless proved unworthy. The testing of this new feature was delightful.

Related Post