3
votes

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 (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 into or out of that section (0 moved in, 0 moved out).'

Here's the code:

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

    if editingStyle == UITableViewCellEditingStyle.Delete {

        let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = delegate.managedObjectContext!

        var error: NSError?

        let fetchRequest = NSFetchRequest(entityName: "Task")

        let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]

        managedContext.deleteObject(fetchedResults[indexPath.row])
        if managedContext.save(&error) == true {

            println("Yes, you did it!")

        }

        //All the above code works fine. 
        table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)


    }
}

UPDATE:

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return tasks.count

}
2
Post your numberOfRowsInSection code - Bannings
It seems like before deleteRowAtIndexPaths is executed, the row is already deleted. I exchanged deleteRowsAtIndexPaths with tableView.reloadData, it works, but it doesn't have animation. - Bright Future
It looks like you are not removing the item from your datasource before numberOfRowsInSection is called again, you have to do this yourself. - Wez

2 Answers

3
votes

You have to update the tasks variable before deleteRowsAtIndexPaths be called:

managedContext.deleteObject(fetchedResults[indexPath.row])
tasks.removeAtIndex(indexPath.row)

table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)
2
votes
  • Problem is you delete data from core data but that data is still in your source array.
  • you have to delete that data from your source array before delete row