Search code examples
iosswiftuitableviewdelete-row

What is the correct way to remove a row from a tableView?


In Xcode 9 I have a tableView with a list of data that is being pulled from CoreData. The adding, editing and saving of data is working correctly, but when I attempt to remove data I encounter a dilemma that is aesthetic on the one and crashes the app on the other.

If I use the following code it deletes the data from CoreData and from the tableview, but without the .fade option. It just vanishes from the tableView.

  override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
         context.delete(tasks[indexPath.row])
         tasks.remove(at: indexPath.row)
         saveTasks()
  }

If I use the following option, the app crashes.

  override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
         context.delete(tasks[indexPath.row])
         tableView.deleteRows(at: [indexPath], with: .fade)
         saveTasks()
  }

How do I apply the .fade option to the remove at: ?


Solution

  • You need to combine those two solutions:

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        context.delete(tasks[indexPath.row])
        tasks.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        saveTasks()
    }
    

    Basically, you have to both update the data (tasks) and tell the tableView to reload.