1

I am trying to implement a delete functionality in my app allowing users to delete information stored in core data and presented through a table view.

here is my code:

 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == .Delete){


    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) //error on this line

        }
}

the error is as follows:

Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UITableView.m:1582
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (6) must be equal to the number of rows contained in that section before the update (6), 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).'


What am I doing wrong? How do I fix this error?

MoralCode
  • 1,954
  • 1
  • 20
  • 42
  • 1
    When you delete rows from tableview you have to delete data from the datasource – mustafa Jan 03 '15 at 17:03
  • I know, but as my data source is CoreData, and the data is being presented through a FetchedResultsController I thought you only had to delete it from the TableView and it would automatically delete it from CoreData... – MoralCode Jan 03 '15 at 17:24
  • No you have to delete it from core data. The delegation eorks only one way from core data to table view. Not from table view to core data – mustafa Jan 03 '15 at 17:26
  • @mstysf you should add that as an answer... – MoralCode Jan 03 '15 at 19:36

1 Answers1

0

Delete the core data item and let the delegate callbacks take care of deleting the table view row:

if editingStyle == .Delete {
  let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
  self.managedObjectContext.deleteObject(item)
}

The row deletion happens in the delegate callback controller:didChangeObject:atIndexPath: forChangeType:newIndexPath:

if type == .Delete { 
  self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
Mundi
  • 79,884
  • 17
  • 117
  • 140
  • Of course you need to code it. Otherwise it won't get compiled and it won't get executed ;-). -- What precisely do you think is "hard-coded" in the callback? – Mundi Jan 04 '15 at 21:44
  • Btw, what code do I put in for the delegate callback? (Sorry, im sorta new to iOS development in swift) – MoralCode Jan 04 '15 at 22:28
  • I wrote the code into my answer... It's not difficult: when the user deletes item, it is deleted from Core Data. The mentioned delegate method is called, checks for the type of change and deletes as necessary. – Mundi Jan 05 '15 at 07:45