我正在尝试应用一个空快照,它使我的应用程序崩溃。我已经尝试调试它 2 天了,但似乎无法找到解决此问题的方法。下面是我正在运行的代码:
//
// ItemsListDiffableVC.swift
// FetchRewardsCodingExercise
//
// Created by Vandan Patel on 11/26/20.
//
import UIKit
final class ItemsListDiffableVC: UIViewController {
private var tableView: UITableView!
private var dataSource: ItemDataSource!
private var groupedItems = [Dictionary<Int, [Item]>.Element]()
var presenter: ItemsListPresentable!
private let cellReusableID = "itemCell"
override func viewDidLoad() {
super.viewDidLoad()
configureTableView()
presenter.didLoadView()
}
private func configureTableView() {
tableView = UITableView()
tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
tableView.backgroundColor = .systemGroupedBackground
tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReusableID)
view.addSubview(tableView)
}
private func configureDataSource() {
dataSource = ItemDataSource(tableView: self.tableView, cellProvider: { (tableView, indexPath, item) -> UITableViewCell? in
let cell = tableView.dequeueReusableCell(withIdentifier: self.cellReusableID, for: indexPath) as! ItemCell
cell.configureCell(withTitle: item.name ?? "")
return cell
})
}
}
extension ItemsListDiffableVC: ItemsListViewable {
func display(groupedItems: [Dictionary<Int, [Item]>.Element]) {
DispatchQueue.main.async {
self.configureDataSource()
self.update(with: groupedItems)
}
}
func display(error: String) {
}
}
extension ItemsListDiffableVC {
private func update(with groupedItems: [Dictionary<Int, [Item]>.Element]) {
var snapshot = NSDiffableDataSourceSnapshot<Section, Item>()
dataSource.apply(snapshot, animatingDifferences: true, completion: nil)
}
}
class Section: Hashable {
let sectionName: String
let identifier = UUID()
init(sectionName: String) {
self.sectionName = sectionName
}
func hash(into hasher: inout Hasher) {
hasher.combine(identifier)
}
static func == (lhs: Section, rhs: Section) -> Bool {
return lhs.identifier == rhs.identifier
}
}
class ItemDataSource: UITableViewDiffableDataSource<Section, Item> {
var groupedItems = [Dictionary<Int, [Item]>.Element]()
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return groupedItems[section].key.sectionTitle
}
}
struct Item: Codable, Hashable {
let id: Int
let listId: Int
let name: String?
}
这是我得到的错误:
*** 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 (0) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 0 deleted).'
我不明白的是为什么在更新之前还有一个部分以及如何处理它。
谢谢。