【发布时间】:2017-12-07 10:00:10
【问题描述】:
我对通过 FetchResultsController 链接到 CoreData 实体的 UICollectionView 有疑问。我有一个带有搜索结果的屏幕,所以我需要从 API 获取记录,刷新核心数据实体并添加新记录。
它工作正常,但有时当我点击搜索按钮太快时,UICollection 会损坏并且不再更新。事实上,当我尝试使用不再存在的元素时发生错误。
我添加了一些检查,但它在 100% 的情况下没有帮助。
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
blockOperations.append(BlockOperation(block: {
if type == .insert {
self.ChatsCollectionView?.insertItems(at: [newIndexPath!])
}
if type == .delete {
if ((indexPath?.row)! <= self.ChatsCollectionView.numberOfItems(inSection: 0) && self.ChatsCollectionView.numberOfItems(inSection: 0) != 0) {
self.ChatsCollectionView?.deleteItems(at: [indexPath!])
}
}
if type == .update {
if ((indexPath?.row)! <= self.ChatsCollectionView.numberOfItems(inSection: 0) && self.ChatsCollectionView.numberOfItems(inSection: 0) != 0) {
self.ChatsCollectionView?.reloadItems(at: [indexPath!])
}
}
if type == .move {
if let indexPath = indexPath {
self.ChatsCollectionView.deleteItems(at: [indexPath])
}
if let newIndexPath = newIndexPath {
self.ChatsCollectionView.insertItems(at: [newIndexPath])
}
}
}))
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
ChatsCollectionView?.performBatchUpdates({
for operation in self.blockOperations {
operation.start()
}
}, completion: { (completed) in
//self.ChatsCollectionView.reloadItems(at: self.ChatsCollectionView.indexPathsForSelectedItems!)
// I comment this, because it cause crash
})
}
所以我现在没有崩溃,但有时我会收到错误,并且 Collection 看起来已损坏(有些行是空的等...):
我不使用 reloadData(),因为当我在 Entity 中刷新数据时它会异步工作并崩溃。
【问题讨论】:
标签: swift core-data nsfetchedresultscontroller flush