简体   繁体   中英

unable to delete object from coredata entity swift

it is deleting data from core data but on deleteRowsAtIndexpaths it gives error which is ['Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (5) must be equal to the number of rows contained in that section before the update (5), 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).']

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if (editingStyle == UITableViewCellEditingStyle.Delete)
        {
            var Id = String()
                if let RowData : NSDictionary = self.SavedJobs[indexPath.row] as? NSDictionary{
                   Id = RowData["vacancy_id"] as! String

                }


            let OptionMenu = UIAlertController(title: "Alert", message: "Vacancy has been deleted", preferredStyle: .Alert)
            let Okay = UIAlertAction(title: "Okay" , style: .Cancel, handler: {
                (alert: UIAlertAction!) -> Void in
                let appDelegate =
                    UIApplication.sharedApplication().delegate as! AppDelegate

                let managedContext = appDelegate.managedObjectContext
                print("saved data pre is \(self.SavedData)")
                let Job = self.SavedData[indexPath.row] as NSManagedObject
                managedContext.deleteObject(Job)
                if (self.SavedData[indexPath.row].deleted){  
                do{
                    try managedContext.save()
                }
                catch{}
                }
                self.SavedJobs.removeObjectAtIndex(indexPath.row)
                self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
                self.DeleteService(Id)
                self.tableView.reloadData()
            })
            OptionMenu.addAction(Okay)
            self.presentViewController(OptionMenu, animated: true, completion: nil)

        }
    }

Have you tried using beginUpdates and endUpdates? ie

        self.tableView.beginUpdates()
        self.SavedJobs.removeObjectAtIndex(indexPath.row)
        self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        self.DeleteService(Id)
        self.tableView.endUpdates()

Also, you dont need to call self.tableview.reloadData() when using deleteRowsAtIndexPaths

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM