Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save borisdipner/e3230ad0fc72fabddfb73cf16a7a4cca to your computer and use it in GitHub Desktop.
Save borisdipner/e3230ad0fc72fabddfb73cf16a7a4cca to your computer and use it in GitHub Desktop.
UICollectionView + NSFetchedResultsController Swift 5
// MARK: NSFetchedResultsController
extension ViewController: NSFetchedResultsControllerDelegate {
var blockOperations: [BlockOperation] = []
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
let insertBlock: () -> Void = { [weak self] in self?.collectionView?.insertItems(at: [newIndexPath!]) }
blockOperations.append(BlockOperation(block: insertBlock))
case .delete:
let deleteBlock: () -> Void = { [weak self] in self?.collectionView?.deleteItems(at: [indexPath!]) }
blockOperations.append(BlockOperation(block: deleteBlock))
case .update:
let reloadBlock: () -> Void = { [weak self] in self?.collectionView?.reloadItems(at: [indexPath!]) }
blockOperations.append(BlockOperation(block: reloadBlock))
case .move:
let moveBlock: () -> Void = { [weak self] in self?.collectionView?.moveItem(at: indexPath!, to: newIndexPath!) }
blockOperations.append(BlockOperation(block: moveBlock))
@unknown default:
fatalError()
}
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
let insertBlock: () -> Void = { [weak self] in self?.collectionView?.insertSections(IndexSet(integer: sectionIndex)) }
blockOperations.append(BlockOperation(block: insertBlock))
case .delete:
let deleteBlock: () -> Void = { [weak self] in self?.collectionView?.deleteSections(IndexSet(integer: sectionIndex))}
blockOperations.append(BlockOperation(block: deleteBlock))
case .update:
let reloadBlock: () -> Void = { [weak self] in self?.collectionView?.reloadSections(IndexSet(integer: sectionIndex))}
blockOperations.append(BlockOperation(block: reloadBlock))
case .move: break
@unknown default:
fatalError()
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
collectionView?.performBatchUpdates({
blockOperations.forEach({ $0.start() })
}, completion: { _ in self.blockOperations.removeAll() })
}
deinit {
blockOperations.forEach({ $0.cancel() })
blockOperations.removeAll()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment