在swift中从tableview中删除项目时出错

时间:2015-01-03 16:53:16

标签: core-data swift ios8 tableview

我正在尝试在我的应用中实现删除功能,允许用户删除存储在核心数据中的信息并通过表格视图显示。

这是我的代码:

 func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == .Delete){


    tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) //error on this line

        }
}

错误如下:

Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-3318.16.14/UITableView.m:1582
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 (6) must be equal to the number of rows contained in that section before the update (6), 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).'


我究竟做错了什么?如何解决此错误?

1 个答案:

答案 0 :(得分:0)

删除核心数据项,让委托回调处理删除表视图行:

if editingStyle == .Delete {
  let item = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
  self.managedObjectContext.deleteObject(item)
}

行删除发生在委托回调controller:didChangeObject:atIndexPath: forChangeType:newIndexPath:

if type == .Delete { 
  self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}