ivanzoid
1/10/2014 - 2:19 PM

Insert & delete rows in UITableView with animation

Insert & delete rows in UITableView with animation

NSMutableArray *indexPathsToDelete = [NSMutableArray new];

for (Object *object in newObjects)
{
	if (![currentObjects containsObject:object]) {
		int row = [newObjects indexOfObject:object];
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
		[indexPathsToDelete addObject:indexPath];
	}
}

NSMutableArray *indexPathsToAdd = [NSMutableArray new];

for (Object *object in currentObjects)
{
	if (![newObjects containsObject:object]) {
		int row = [currentObjects indexOfObject:object];
		NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
		[indexPathsToAdd addObject:indexPath];
	}
}

[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView insertRowsAtIndexPaths:indexPathsToAdd withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];