删除部分中的最后一个单元格后,iOS应用程序崩溃
所以我每次尝试删除该部分的最后一个单元格时都会崩溃。
例如,如果我的部分有10行,我可以删除它们没有任何问题,但最后一个抛出以下错误:
由于未捕获的exception“NSInternalInconsistencyException”而终止应用程序,原因是:“无效的更新:节数无效。 更新(1)后,表视图中包含的段数必须等于更新前(3)的表视图中包含的段数,加上或减去插入或删除的段数(0插入,0删除)。”
我在这里search了一下,发现了一些方法来解决这个问题,但我试了一下,不能解决这个问题,它仍然崩溃,并抛出相同的错误。
我的代码的相关部分如下所示:
override func numberOfSections(in tableView: UITableView) -> Int { if (main_arr.count > 0 && sub_arr.count > 0) { self.numberOfSections = 3 } else { self.numberOfSections = 2 } return self.numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return 1 } else if (section == 1 && main_arr.count > 0) { return main_arr.count } else { return sub_arr.count } } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { switch indexPath.section { case 1: main_arr.remove(at: indexPath.row) case 2: sub_arr.remove(at: indexPath.row) default: print("default 001") } tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } }
编辑1
我试图处理全局variables,负责numberOfSections所以当我的任何array.count == 0它将减less1,但它没有解决问题。
我完全理解错误信息,如果我有3个部分,并且删除了其中一个部分的全部内容,我应该删除一个部分,并从数据源中删除它。
问题是numberOfSections
在删除行之前和之后返回不同的值,但是不删除任何部分 。 所以你应该在numberOfSections中返回一个常量值,或者在deleteRows
调用deleteSections
主要要记住的是以下几点:
UITableView必须始终包含与您的dataSource相同数量的行和部分。
你不能只返回一个新的值在numberOfSections
或numberOfRows
数据源方法。 每个改变都应该用删除/插入行(部分)方法来补偿。 反之亦然:如果您删除/插入tableView,则必须在dataSource方法中返回相应的值。 正如你的例外信息所述:
更新(1)后 ,表视图中包含的段数必须等于更新前(3)的表视图中包含的段数,加上或减去插入或删除的段数(0插入,0删除) 。
这是因为3 + 0≠1 在这种情况下,您应该删除两个部分以避免崩溃。
错误信息其实非常有帮助。 它谈到部分 – 它预计不会改变,但它发现后,您的操作有不同的价值。
基本上,UIKit在调用你的代码之前检查了部分和行的数量,运行你的代码,然后检查新的数字是否与你的操作一致。 在你的情况下,它不会 – 因为你调用deleteRows
(这应该减less给定部分的行数),但是你的numberOfSections
委托现在给出了不同的结果。 所以你要么调用deleteSections
要么保持sectionCount不被修改。
顺便说一句,不禁止返回0
作为一个部分的行数 – 也许这正是你想要的。
进一步的说明:我不认为将实例variables中的段数存储在这里是一件好事。 它使双重簿记。
- CoreData删除多个对象
- 我怎样才能解密在iOS的XML文件与AES / CBC / PKCS5Padding标准,在Android的文件已被解密,所有的关键像盐,IV
- 使用自定义UITableViewCell中的button获取单元格string的问题
- 无法理解NSError / NSObject指针传递行为
- MPMoviePlayerController忽略全屏模式不适用于iOS 6
- Swift中的网络层
- 我可以在我的Cocos2D-iPhone游戏中支持VoiceOver吗?
- Google Drive Sdk – iOS应用程序中的audio和videostream式传输
- 在SceneKit中点击/select节点(Swift)