【问题标题】:Error when deleting item from tableview in swift快速从表格视图中删除项目时出错
【发布时间】:2015-01-03 16:53:15
【问题描述】:

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

这是我的代码:

 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).'


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

【问题讨论】:

  • 当您从 tableview 中删除行时,您必须从数据源中删除数据
  • 我知道,但是由于我的数据源是 CoreData,并且数据是通过 FetchedResultsController 呈现的,我以为您只需从 TableView 中删除它,它就会自动从 CoreData 中删除它...
  • 不,您必须从核心数据中删除它。委派从核心数据到表视图只有一种方式。不是从表视图到核心数据
  • 好的...我会试试的。
  • @mstysf 您应该将其添加为答案...

标签: core-data swift ios8 tableview


【解决方案1】:

删除核心数据项并让委托回调负责删除表格视图行:

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)
}

【讨论】:

  • 当然需要编码。否则它不会被编译,也不会被执行;-)。 -- 你认为回调中的“硬编码”究竟是什么?
  • 顺便说一句,我为委托回调输入了什么代码? (抱歉,我对 Swift 的 iOS 开发有点陌生)
  • 我把代码写到了我的答案中......这并不难:当用户删除项目时,它会从核心数据中删除。提到的委托方法被调用,检查更改的类型并根据需要删除。
猜你喜欢
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 2016-09-21
  • 1970-01-01
相关资源
最近更新 更多