Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wanbok/735bb110d16b4833cb0b to your computer and use it in GitHub Desktop.
Save wanbok/735bb110d16b4833cb0b to your computer and use it in GitHub Desktop.
Swift: NSFetchedResultsControllerDelegate for UITableView
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
...
}
// MARK: - NSFetchedResultsControllerDelegate
extension ViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .Update:
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
case .Move:
tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath)
// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment