我试图在网络调用后更新集合视图,以将更多元素插入集合视图中。只有一节(第 0 节)。崩溃很难重现,我无法确切说明为什么会发生这种情况。该代码也是按照 Raywenderlich 的 answer 中建议的方式以及此 stackoverflow answer
建议的方式编写的这是我的代码:
func process(_ difference: [CollectionDifference<User>.Change]?) {
guard let difference = difference, !difference.isEmpty else {
updateDataSource()
collectionView.reloadData()
return
}
let deleting = difference.contains { change in
if case let .remove(offset: _, element: _, associatedWith: associatedWith) = change {
return associatedWith == nil
}
return false
}
let inserting = difference.contains { change in
if case let .insert(offset: _, element: _, associatedWith: associatedWith) = change {
return associatedWith == nil
}
return false
}
isCollectionViewUpdating = true
collectionView.performBatchUpdates({
updateDataSource()
for change in difference {
switch change {
case let .insert(offset: offset, element: recommendation, associatedWith: _):
collectionView.insertItems(at: [IndexPath(row: offset, section: 0)])
case let .remove(offset: offset, element: _, associatedWith: _):
collectionView.deleteItems(at: [IndexPath(row: offset, section: 0)])
}
}
}, completion: { [weak self] _ in
guard let self = self else { return }
self.isCollectionViewUpdating = false
self.finalizingIndexPaths.removeAll()
if deleting {
self.paginate()
} else if inserting {
self.delegate?.didInsertInCollectionView()
}
})
}
这是我遇到的错误消息
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid batch updates detected: the number of sections and/or items returned by the data source before and/or after performing the batch updates are inconsistent with the updates.
Data source before updates = { 1 section with item counts: [16] }
Data source after updates = { 1 section with item counts: [16] }
Updates = [
Insert item (0 - 0),
Insert item (0 - 1),
Insert item (0 - 2),
Insert item (0 - 3),
Insert item (0 - 4),
Insert item (0 - 5),
Insert item (0 - 6),
Insert item (0 - 7),
Insert item (0 - 8),
Insert item (0 - 9),
Insert item (0 - 10),
Insert item (0 - 11),
Insert item (0 - 12),
Insert item (0 - 13),
Insert item (0 - 14),
Insert item (0 - 15)
]
此外,包含 collectionView 的特定视图控制器将作为子视图控制器添加到其父视图控制器中。父视图控制器是选项卡栏控制器的一部分。
有处理 uicollectionview 的回调
public func willBecomeActive() {
view.layoutIfNeeded()
collectionView.reloadData()
// need to add this empty performBatchUpdates, otherwise the cells don't
// come on screen in tests
collectionView.performBatchUpdates({}, completion: nil)
}
public func didResignActive() {
collectionView.reloadData()
}
override public func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionViewFlowLayout.updateItemSize()
// helps to correctly resizes the cells.
UIView.performWithoutAnimation {
collectionView.performBatchUpdates({}, completion: nil)
}
}
有人可以发现我的代码的问题并提供帮助吗?
我尝试用新用户加载collectionview并替换旧用户。我期待新用户成功插入。但有时我会遇到难以解释的崩溃。崩溃的错误消息如上
不知道您是否已经解决了这个问题,但在我看来,您收到的错误告诉您您正在尝试插入或删除项目,即使您的集合视图的源没有改变。如果没有看到更多,很难判断这是否真的是问题所在