Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save raypendergraph/d7eba27aa9da113b007d5d685e26f4ea to your computer and use it in GitHub Desktop.
Save raypendergraph/d7eba27aa9da113b007d5d685e26f4ea to your computer and use it in GitHub Desktop.
A sort of generic FetchedResultsController delegate.
import UIKit
import CoreData
class GenericTableFetchResultsController: NSObject {
fileprivate var tableView: UITableView!
fileprivate var rowAnimation: UITableViewRowAnimation!
init(tableView: UITableView, rowAnimation: UITableViewRowAnimation) {
self.tableView = tableView
self.rowAnimation = rowAnimation
}
}
extension GenericTableFetchResultsController: NSFetchedResultsControllerDelegate {
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
DispatchQueue.main.async {
guard let path = newIndexPath else {
assertionFailure("CoreData Issue: newIndexPath should be here on insert.")
return
}
self.tableView.insertRows(at: [path], with: self.rowAnimation)
}
case .update:
DispatchQueue.main.async {
guard let path = indexPath else {
assertionFailure("CoreData Issue: indexPath should be here on update.")
return
}
self.tableView.reloadRows(at: [path], with: self.rowAnimation)
}
case .move:
DispatchQueue.main.async {
guard let oldPath = indexPath, let newPath = newIndexPath else {
assertionFailure("CoreData Issue: Both indexPaths are required for a move.")
return
}
self.tableView.moveRow(at: oldPath, to: newPath)
}
case .delete:
DispatchQueue.main.async {
guard let path = indexPath else {
assertionFailure("CoreData Issue: indexPath should be here on delete.")
return
}
self.tableView.deleteRows(at: [path], with: self.rowAnimation)
}
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
DispatchQueue.main.async {
self.tableView.insertSections(IndexSet(integer: sectionIndex), with: self.rowAnimation)
}
case .update:
DispatchQueue.main.async {
self.tableView.reloadSections(IndexSet(integer: sectionIndex), with: self.rowAnimation)
}
case .delete:
DispatchQueue.main.async {
self.tableView.deleteSections(IndexSet(integer: sectionIndex), with: self.rowAnimation)
}
default: break
}
}
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
DispatchQueue.main.async {
self.tableView.beginUpdates()
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
DispatchQueue.main.async {
self.tableView.endUpdates()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment