【问题标题】:Dispatch.main.asyncAfter() crash app when called before it's finishedDispatch.main.asyncAfter() 在完成之前调用崩溃应用程序
【发布时间】:2017-07-27 20:53:24
【问题描述】:

所以我有一个带有单选按钮的应用程序来检查任务,只要我让动画完成,一切都会按预期工作,但是如果我同时按下两个按钮,我会收到错误:

libc++abi.dylib:以 NSException 类型的未捕获异常终止

每次点击单选按钮时执行的代码

   func RadioTapped(_ cell: TableViewCell) {


    if let indexPath = tableView.indexPath(for: cell) {
        // Removes task from coreData
        let task = self.tasks[indexPath.row]
       print(tasks.count)
        self.context.delete(task)
        print(tasks.count)
        (UIApplication.shared.delegate as! AppDelegate).saveContext()
        do{
            self.tasks = try self.context.fetch(TodayTask.fetchRequest())

            // Animates the removal of task cell
            DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(800),execute: {
                self.tableView.beginUpdates()
                self.tableView.deleteRows(at: [indexPath], with: .fade)
                self.tableView.endUpdates()
            })

        } catch {
            print("Fetching Failed")
        }
    }


}

错误信息

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

【问题讨论】:

  • 在模拟器上运行它以获取错误日志..
  • 我在模拟器上运行了,但是在哪里可以找到日志?
  • 您需要显示与异常相关的消息,它会告诉您出了什么问题,但我会说asyncAfter 是代码异味;你不应该需要时间延迟
  • Paulw11 是对的。还可以尝试在主块中移动 `self.tasks = try self.context.fetch(TodayTask.fetchRequest())' 并查看。

标签: ios swift crash


【解决方案1】:

表格行删除操作也需要删除表格数组的元素。

根据您的代码,self.tasks 可能是您的表格列表的数组。

从相同的索引中删除“self.tasks”的一个元素,您要为其删除行。

提示:

// Remove array element
self.tasks.remove(at: <index.row>)


DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(800),execute: {
                self.tableView.beginUpdates()
                self.tableView.deleteRows(at: [indexPath], with: .fade)
                self.tableView.endUpdates()
            })

【讨论】:

  • 清楚地写了self.context.delete(task)和之后self.tasks = try self.context.fetch(TodayTask.fetchRequest())
  • 不会 self.context.delete(task) 删除 indexPath 处的任务吗?
  • @SalmanGhumsani 同意你的看法。它从上下文重新启动数组。但需要确保,没有。删除操作之前的数组元素数
  • 当我打印 tasks.count 我得到 13, 13 然后 12 12
  • @J-Doe Pl。添加您有问题的打印声明,以便我可以更好地帮助您。您的错误消息说,删除操作执行了两次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 2012-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多