我正在为我的消息传递应用程序使用领域快速。我的消息传递基本视图是自定义UICollectionView,我使用领域swift进行数据存储。不幸的是,我无法从领域找到任何官方示例来通过领域通知更新集合视图。因此,当我从领域中获取消息并通过添加该领域列表的观察者来获取 notificationToken 时,我就这样实现了,因此当更新来自该通知时,我将执行批量更新并删除,插入和修改领域告诉我的索引在此通知中执行。我的应用程序在测试环境中运行良好,但是在生产环境中,我遇到了一些崩溃,按结构报告我的崩溃,告诉我应用程序崩溃,这是由此批更新引起的。他们的邮件大多像
invalid update: invalid number of sections. The number of sections contained in the collection view after the update (1) must be equal to the number of sections contained in the collection view before the update (1), plus or minus the number of sections inserted or deleted (0 inserted, 1 deleted).
或 更新后部分中无效的项目数等等。 我现在很困惑。有什么想法吗?
我执行此更新的代码
notificationToken = dbmsgs?.observe { [weak self] (changes: RealmCollectionChange) in
switch changes{
case .initial:
print("intial")
self?.collectionView.reloadData()
case .update(_,let deletions,let insertions,let modifications):
self?.collectionView.performBatchUpdates({
if deletions.count > 0{
print("deletions count\(deletions.count)")
if (self?.collectionView.numberOfItems(inSection: 0) ?? 0) - deletions.count > 0 {
self?.collectionView.deleteItems(at: deletions.map { IndexPath(row: $0, section: 0) })
}
else{
self?.collectionView.deleteSections(IndexSet(integer: 0))
}
}
if insertions.count > 0{
print("insertaions count\(insertions.count)")
for index in insertions{
guard let lastdbmsg = self?.dbmsgs?[index] else{
return
}
let sectionIndex = 0
let itemIndex = ( self?.dbmsgs != nil) ? (self?.dbmsgs?.count)! - 1 : 0
if itemIndex == 0{
self?.collectionView.insertSections([0])
}
self?.collectionView.insertItems(at: [IndexPath(item: itemIndex, section: sectionIndex)])
if itemIndex != 0{
self?.collectionView.reloadItems(at: [IndexPath(row: itemIndex-1, section: 0)])
}
}
}
if modifications.count > 0{
self?.collectionView.reloadItems(at: modifications.map({ IndexPath(row: $0, section: 0)}))
}
},completion: { (_) in
})
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
}