Delete row on index path error

Application terminated due to unmapped exception "NSInternalInconsistencyException", Reason: "Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after update (1) must equal the number of rows contained in this section before updating (1 ), plus or minus the number of rows inserted or deleted from this section (0 inserted, 1 deleted) and plus or minus the number of rows moved to or from this section (0 moved to, 0 dropped).

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

}

      

+3


source to share


2 answers


You need to update the variable tasks

to deleteRowsAtIndexPaths

:



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

table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)

      

+1


source


  • The problem is that you are removing data from core data

    , but that data is still in your original array.
  • you need to remove this data from the original array before deleting the row


+1


source







All Articles