1

In Objective-C I have used the following code when deleting a row from a tableView and it works just fine.

Objective-C Example

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.arrayName removeObjectAtIndex:indexPath.row];
    [self.tableName reloadData];
}

I recently made a search to see how this was done in Swift and I noticed that most of the code I found is different than what I used before.

Swift Example

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == UITableViewCellEditingStyle.Delete {
      numbers.removeAtIndex(indexPath.row)    
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
   }
}

So now the question is, have I been doing it wrong or both ways are ok?

What is the correct way in either language (Swift or Objective-C)?

fs_tigre
  • 10,650
  • 13
  • 73
  • 146

2 Answers2

4

The Objective-C code works but isn't really the proper way. It should be just like the sample Swift code you posted.

Regardless of the language, the check for the editing style is optional. It depends on what your table view supports. If you only delete and don't support insert, there's little benefit to verifying the editing style parameter. Of course it's safer to check, just in case you add insertion later on.

And using reloadData on a table when deleting a single row is just inefficient and possibly a bad UX.

tl;dr - The Objective-C code works but is far from ideal. The Swift code is much better overall.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
3

Using deleteRowAtIndexPaths is the correct way. If you simply reload the tableview, the row that was deleted will abruptly disappear, instead of being animated out.

raf
  • 2,569
  • 20
  • 19