0

I have a similar problem to - Delete Data from Coredata Swift.

I'm trying to delete a row from a table view and I do get the following error:

Terminating app due to uncaught exception NSInternalInconsistencyException" reason - attempt to delete row 0 from section 0 which only contains 0 rows before the update

My code is at it follows:

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

   let context: NSManagedObjectContext = self.fetchedResultsController.managedObjectContext
   NSLog("numberOfRowsInSection %d", self.tableView.numberOfRowsInSection(o))

   if editingStyle == .Delete
   {

       let alertController = UIAlertController(title: "Delete menu item", message: "Are you sure you want to delete \((self.fetchedResultsController.fetchedObjects as [Menu])[indexPath.row].menuText)?", preferredStyle: UIAlertControllerStyle.Alert)

       let defaultAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {
             (action: UIAlertAction!) -> Void in
             context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject)
             var menus = self.fetchedResultsController.fetchedObjects as [Menu]
             menus.removeAtIndex(indexPath.row)
             context.save(nil)

             NSLog("numberOfRowsInSection %d", self.tableView.numberOfRowsInSection(o))
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
            tableView.reloadData()
       });

       alertController.addAction(defaultAction)
       presentViewController(alertController, animated: true, completion: nil)
   }
}

Could anyone provide me some help? Thank you in advance!

Victor Sigler
  • 23,243
  • 14
  • 88
  • 105
  • 1
    Try the answer of Martin in this question http://stackoverflow.com/questions/29331345/delete-uitableviewcell-with-animation-error-crash/29331422#29331422. I hope this help you – Victor Sigler Apr 06 '15 at 16:25
  • 1
    Are you not removing it twice? You call `context.deleteObject`, so the object is deleted. Then you assign menus as the fetchedObjects and try to delete it again with `menus.removeAtIndex()`. The whole `menus` thing seems unnecessary. If anything, you just need to refetch, and do it before you delete the tableview row. – user2320861 Apr 06 '15 at 16:31
  • Yes, that's it. Thank you very much. It seems the data were retrieved from the context directly and it was no longer needed to call the deleteRowsAtIndexPaths + removeAtIndex both methods – Bogdan Turtoi Apr 07 '15 at 08:59

0 Answers0