How to delete row in tableView with CoreData data

0

I'm making an app that stores information in CoreData and shows it to the user in a table. I added the function of deleting rows when swiping, but I am having problems to achieve the result.

My code is this:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        guard let appDelegate =
            UIApplication.shared.delegate as? AppDelegate else {
                return
        }

        let managedContext =
            appDelegate.persistentContainer.viewContext

        if editingStyle == .delete {
            print(results.count)
            let remove = results[indexPath.row]
            managedContext.delete(remove)

            do {
                try managedObjectContext.save()

            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
            }

            tableView.beginUpdates()
            tableView.deleteRows(at: [indexPath], with: .automatic)
            tableView.endUpdates()

        }
    }

The error he gives me is:

  

'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved in or out of that section (0 moved in, 0 moved out). '

I understand that it tells me that the information of the array that generates the table is not being erased, but as I understand it should be deleted in this line managedContext.delete(remove) or am I wrong? What is the error?

Thanks

    
asked by Enrique 21.12.2017 в 12:04
source

1 answer

0

Try using NSFetchedResultsController, it is a very powerful tool and with which you can save a lot of work since it automatically responds to the events that happen in the database: delete, insert, update.

Here is a tutorial on NSFetchedResultsController: link

And in this section is where they deal with data deletion: link

    
answered by 30.12.2017 / 17:25
source