Ios – How to delete row in UITableView and update indexPaths without calling reloadData

animationiosrowuitableview

[UPDATE]

I've found the problem. I've created a custom UITableViewCell, and am not using the standard methods to trigger deletion. My custom UITableViewCell has a custom indexPath property that I populate when creating the cell. That's why it doesn't get updated without a call to reload data.

As a workaround, to minimize code rewriting, I'm using the solution marked as the answer.

[/UPDATE]

I've seen other questions similar to this, but not quite the same…

I have a UITableView that gets it's rows (cells) from objects in a NSArray. The rows are mapped to the NSArray using the indexPath.row. This means that the object at index 0 in the NSArray corresponds to the cell with indexPath.row 0.

Whenever I delete a row, I remove the object from the NSArray (as seen in many examples, including Apple's documentation).

The problem is, whenever a row is removed, the indexPath's aren't updated. For example:

I have a table view with 3 rows. This means I have indexPath.row 0, 1 and 2. Also, the corresponding NSArray objects a index 0, 1 and 2.

When I delete row 1 from the UITableView and remove the corresponding object in the NSArray, what remains is indexPath.row 1 and 2, but the the indexes for the NSArray are 0 and 1.

If I try to delete what is now the second row from the UITableView, I run into a problem because it's indexPath.row is 2, but the corresponding object in the NSArray has index 1.

To put it another way, the indexPath.row and object indexes are no longer "in sync".

People have suggested using UITableView's reloadData method… This, in fact, does "reset" the indexPaths, but interrupts the UITableView row animation.

How can I do a row delete, update the indexPaths and still maintain the UITableView's animations?!

Best Answer

Not tested, but a couple things I can think of are either delay the reload until the animations complete. Or just reload those rows rather than the whole table using:

- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation

Delay:

[tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.5];
Related Topic