I have an issue with UICollectionView that linked to CoreData Entity via FetchResultsController. I have a screen with search results, so i need to get records from API, flush Core Data Entity and add new records.
It works fine, but sometimes when i click search button too fast UICollection becomes broken and does not updates anymore. It's a fact that error occurred when i am trying to work with elements that does not exists anymore.
I've added some checks, but it not helps in 100% of situations.
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
})
}
So i have no crashes now, but sometimes i get errors and Collection looks damaged (some rows are emty etc...):
I don't use reloadData() because it works async and crash when i flush data in Entity.