我正试图围绕DiffableDataSource
在 tableviews/collectionviews 中处理数据的新方法,在测试期间我遇到了一个奇怪的崩溃。我希望下面的两种实现方式完全相同:
实施1:
class DiffableSection {
var id: String
var items: [AnyDiffable]
init(id: String,
items: [AnyDiffable] = []) {
self.id = id
self.items = items
}
}
extension DiffableSection: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
extension DiffableSection: Equatable {
static func == (lhs: DiffableSection, rhs: DiffableSection) -> Bool {
return lhs.id == rhs.id
}
}
实施2:
class DiffableSection: NSObject {
var id: String
var items: [AnyDiffable]
init(id: String,
items: [AnyDiffable] = []) {
self.id = id
self.items = items
}
// MARK: - Hashable and Equatable
public override var hash: Int {
var hasher = Hasher()
hasher.combine(id)
return hasher.finalize()
}
public override func isEqual(_ object: Any?) -> Bool {
guard let object = object as? DiffableSection else { return false }
return id == object.id
}
}
但显然它们不是 -Implementation 2
与下面的代码一起使用并且Implementation 1
不使用。
func apply(_ sections: [DiffableSection]) {
var snapshot = self.snapshot()
for section in sections {
snapshot.appendSectionIfNeeded(section)
snapshot.appendItems(section.items, toSection: section)
}
apply(snapshot)
}
(...)
extension NSDiffableDataSourceSnapshot {
mutating func appendSectionIfNeeded(_ identifier: SectionIdentifierType) {
if sectionIdentifiers.contains(identifier) { return }
appendSections([identifier])
}
}
运行时收到的崩溃消息Implementation 1
:
'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: section != NSNotFound'
有人可以解释一下这些实现有什么区别吗?我怎样才能修复Implementation 1
与工作相同的问题Implementation 2
?