iOS UITableView添加数据后更新提示section数量不匹配错误如何解决?
'Invalid update: invalid number of sections. The number of sections contained in the table view after the update (1) must be equal to the number of sections contained in the table view before the update (0), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'
问题根源
报错本质是UITableView执行更新操作时的数据源校验不通过:你插入行时指定了分组为0,但是更新操作执行前,你的数据源返回的分组数量是0,更新操作后分组数量变成了1,期间你没有执行过任何插入/删除分组的操作,系统判定更新前后分组数量不匹配,直接抛出异常。
修复方案
- 首先调整UITableView的数据源方法
numberOfSections(in:)的返回逻辑:
如果你整个列表只有1个固定分组,直接固定返回1即可;如果你的分组数量是根据noticeLists是否为空动态判断(空时返回0,有数据时返回1),那你首次添加数据时需要先插入分组,再插入行。 - 优化列表更新逻辑,避免循环单条插入行,批量处理性能更高,也能减少UI重复渲染:
DispatchQueue.main.async { guard let records = jsonDict["records"] as? [Any], let data = try? JSONSerialization.data(withJSONObject: records, options: []) else { self.chkList() return } do { let noticeData = try decoder.decode([NoticeModel].self, from: data) // 记录插入前的数组长度,作为插入行的起始位置 let originCount = self.noticeLists.count // 批量构造新数据追加到数据源数组 let newNoticeList = noticeData.map { Notice(title: $0.title, date: $0.createdAt, description: $0.content, isOpened: false) } self.noticeLists.append(contentsOf: newNoticeList) // 动态分组场景:之前无数据,现在首次加数据需要先插入分组 if originCount == 0 { self.noticeTableView.insertSections(IndexSet(integer: 0), with: .automatic) } // 构造要插入的所有行的IndexPath,批量插入 else { let insertIndexPaths = (originCount..<self.noticeLists.count).map { IndexPath(row: $0, section: 0) } self.noticeTableView.beginUpdates() self.noticeTableView.insertRows(at: insertIndexPaths, with: .automatic) self.noticeTableView.endUpdates() } } catch { print("数据解析失败: \(error.localizedDescription)") } self.chkList() }
- 额外校验项:确保
tableView(_:numberOfRowsInSection:)方法的返回值严格等于noticeLists.count,不要硬编码行数。
内容的提问来源于stack exchange,提问作者hong4383
相关产品推荐
相关产品推荐

