在swift中从tableview中删除项目时出错 [英] Error when deleting item from tableview in swift

查看:153
本文介绍了在swift中从tableview中删除项目时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to implement a delete functionality in my app allowing users to delete information stored in core data and presented through a table view.

这里是我的代码:

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



我做错了什么?如何修复此错误?


What am I doing wrong? How do I fix this error?

推荐答案

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

Delete the core data item and let the delegate callbacks take care of deleting the table view row:

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

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

The row deletion happens in the delegate callback controller:didChangeObject:atIndexPath: forChangeType:newIndexPath:

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

这篇关于在swift中从tableview中删除项目时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆