试图从核心数据中删除实体,我得到......?

时间:2016-01-07 18:08:45

标签: ios core-data nsmanagedobject

我正在尝试从核心数据中删除实体,但我收到以下错误:

    The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (10), 
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).'

这是我的tableview函数

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

        let deletedRow:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!

        if editingStyle == UITableViewCellEditingStyle.Delete {

            // remove the deleted item from the model
            moContext.deleteObject(scannedVisitors[indexPath.row] as NSManagedObject)
            scannedVisitors.removeAtIndex(indexPath.row)
            do {
                try moContext.save()
                print("deleted and saved")
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
                abort()
            }     
             // remove the deleted item from the `UITableView`
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            deletedRow.accessoryType = UITableViewCellAccessoryType.None
            print("Deleted + accessory")
        }

    }

我在viewDidAppear中有fetchRequest而不在viewDidLoad中

override func viewDidAppear(animated: Bool) {

    do {
        let request =  NSFetchRequest(entityName: "ScannedVisitor")

        scannedVisitors = try moContext.executeFetchRequest(request) as! [ScannedVisitor]

        self.tableView.reloadData()

    } catch let error as NSError  {
        print(error)
    }

}

当我重新启动应用程序时,实体已被删除,但在删除操作期间,我收到运行时错误。 我该如何解决这个问题?

[编辑]仔细看看我看到这部分被解析了#34; 3次

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

    print("Rows \(scannedVisitors.count)")
    return scannedVisitors.count
}

因为它打印

Rows 0
Rows 0
Rows 6

1 个答案:

答案 0 :(得分:1)

在保存上下文之前,不要从视图中删除要删除的对象,从模型中获取该对象并执行有关UI的所有删除任务。

let objectToDelete = scannedVisitors[indexPath.row]
scannedVisitors.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic)
moContext.deleteObject(objectToDelete)
do {
  try moContext.save()
...

实际上,不需要更改将要移除的单元的附件类型