首页 > 解决方案 > 在 Swift 中删除分组表中的行时崩溃

问题描述

我正在学习使用 Swift 编写代码的教程。在其中,我被要求创建一个数组数组,用于创建一个分组表。例如 var emojis = [[emojiarray1],[emojiarray2],[emojiarray3]]

稍后的练习要求我合并代码,以便滑动将从表视图中删除一行。这是我在帮助执行此过程的函数中拥有的内容:

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            emojis.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .automatic)
}

但是,当我滑动以删除一行时,我没有删除行,而是应用程序崩溃并显示以下消息:线程 1:信号 SIGABRT

在控制台中我得到

 *** Assertion failure in -[UITableView _Bug_Detected_In_Client_Of_UITableView_Invalid_Number_Of_Sections:]

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (7) must be equal to the number of sections contained in the table view before the update (8), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'

它说“无效的部分数”,但我没有删除一个部分,只删除一个部分中的一行。我在想也许这emojis.remove(at: indexPath.row)条线可能已经删除了一个部分,但我真的不知道那是否属实,或者如何修复它。

标签: iosswiftuitableview

解决方案


从表中删除一行但从数组中删除一个部分,您可能需要

emojis[indexPath.section].remove(at: indexPath.row)

推荐阅读