Reputation: 4914
I am trying to delete an entity from core data but i am getting the following error:
The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (10),
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 into or out of that section (0 moved in, 0 moved out).'
Here is my tableview function
// MARK: delete
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let deletedRow:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
if editingStyle == UITableViewCellEditingStyle.Delete {
// remove the deleted item from the model
moContext.deleteObject(scannedVisitors[indexPath.row] as NSManagedObject)
scannedVisitors.removeAtIndex(indexPath.row)
do {
try moContext.save()
print("deleted and saved")
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
// remove the deleted item from the `UITableView`
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
deletedRow.accessoryType = UITableViewCellAccessoryType.None
print("Deleted + accessory")
}
}
I have the fetchRequest in viewDidAppear and not in viewDidLoad
override func viewDidAppear(animated: Bool) {
do {
let request = NSFetchRequest(entityName: "ScannedVisitor")
scannedVisitors = try moContext.executeFetchRequest(request) as! [ScannedVisitor]
self.tableView.reloadData()
} catch let error as NSError {
print(error)
}
}
When i restart the app the entity has been deleted, but during the deletion action i get the runtime error. How can i fix this?
[EDIT] taking a closer look i am seeing this part being "parsed" 3 times
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("Rows \(scannedVisitors.count)")
return scannedVisitors.count
}
because it prints
Rows 0
Rows 0
Rows 6
Upvotes: 0
Views: 37
Reputation: 285069
Don't get the object to be deleted from the view, get it from the model and do all deletion tasks regarding the UI before saving the context.
let objectToDelete = scannedVisitors[indexPath.row]
scannedVisitors.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic)
moContext.deleteObject(objectToDelete)
do {
try moContext.save()
...
Actually it's not needed to change the accessory type of a cell which is going to be removed anyway
Upvotes: 1