无法从coredata实体swift中删除对象

时间:2016-09-23 07:37:15

标签: ios swift core-data

它正在从核心数据中删除数据,但在deleteRowsAtIndexpaths上它会出现错误,这是['无效更新:第0部分中的无效行数。更新后现有部分中包含的行数(5)必须等于更新前的该部分中包含的行数(5),加上或减去从该部分插入或删除的行数(0插入,1删除)和加或减行数移入或移出该部分(0移入,0移出)。']

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)

        }
    }

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用beginUpdates和endUpdates?即

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

此外,使用self.tableview.reloadData()

时,您无需致电deleteRowsAtIndexPaths