【问题标题】:Delete row at index path error删除索引路径错误处的行
【发布时间】:2015-06-16 12:35:16
【问题描述】:

由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无效更新:第0节中的行数无效。更新(1)后现有节中包含的行数必须等于行数更新前包含在该节中 (1),加上或减去从该节插入或删除的行数(0 插入,1 删除),加上或减去移入或移出该节的行数(0 移入, 0 移出)。'

代码如下:

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

    if editingStyle == UITableViewCellEditingStyle.Delete {

        let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = delegate.managedObjectContext!

        var error: NSError?

        let fetchRequest = NSFetchRequest(entityName: "Task")

        let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as! [NSManagedObject]

        managedContext.deleteObject(fetchedResults[indexPath.row])
        if managedContext.save(&error) == true {

            println("Yes, you did it!")

        }

        //All the above code works fine. 
        table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)


    }
}

更新:

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

    return tasks.count

}

【问题讨论】:

  • 发布您的numberOfRowsInSection 代码
  • 似乎在执行 deleteRowAtIndexPaths 之前,该行已被删除。我用 tableView.reloadData 交换了 deleteRowsAtIndexPaths,它可以工作,但它没有动画。
  • 在再次调用 numberOfRowsInSection 之前,您似乎没有从数据源中删除该项目,您必须自己执行此操作。

标签: ios swift tableview


【解决方案1】:

您必须在调用deleteRowsAtIndexPaths 之前更新tasks 变量:

managedContext.deleteObject(fetchedResults[indexPath.row])
tasks.removeAtIndex(indexPath.row)

table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Fade)

【讨论】:

  • 太好了,现在可以使用了。我用 tasks = managedContext.executeFetchRequest(fetchRequest, error: &error) 作为! [NSManagedObject] 来更新它,还有其他语法可以实现吗?
  • @BrightFuture 你的工具简单高效。
  • @BrightFuture 请接受我的回答,您可以点击投票下方左边的勾(对勾)
  • 错误屏幕:由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 0 节中的行数无效。更新后现有节中包含的行数 (3)必须等于更新前该节中包含的行数 (3),加上或减去从该节中插入或删除的行数(0 插入,2 删除),加上或减去移入的行数或离开该部分(0 移入,0 移出)。'
【解决方案2】:
  • 问题是您从core data 中删除了数据,但该数据仍在您的源数组中。
  • 您必须在删除行之前从源数组中删除该数据

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 2021-06-14
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多