Boilerplate for NSFetchedResultsControllerDelegate and tableview, fading in all changes
import Foundation
import UIKit
import CoreData
class TableFetchedResultsControllerDelegate: NSObject, NSFetchedResultsControllerDelegate {
let tableView:UITableView
init(tableView:UITableView) {
self.tableView = tableView
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch(type) {
case .insert:
if let newIndexPath = newIndexPath {
tableView .insertRows(at: [newIndexPath], with: .fade)
}
case .delete:
if let indexPath = indexPath {
tableView .deleteRows(at: [indexPath], with: .fade)
}
case .update:
if let indexPath = indexPath {
tableView.reloadRows(at: [indexPath], with: .fade)
}
case .move:
if let indexPath = indexPath {
tableView .deleteRows(at: [indexPath], with: .fade)
}
if let newIndexPath = newIndexPath {
tableView .insertRows(at: [newIndexPath], with: .fade)
}
}
}
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch(type) {
case .insert:
tableView.insertSections(IndexSet(integer: sectionIndex), with: .fade)
case .delete:
tableView.deleteSections(IndexSet(integer: sectionIndex), with: .fade)
default:
break
}
}
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}