Reputation: 63
I have created the table "tableView" (data from CoreData - NSManagedObject). I want to update the data in the tables when the new notification comes from NSNotification without refreshing the table completely. How to do it ?
Thanks for help!
Upvotes: 0
Views: 112
Reputation: 16327
If you want to back tableview with autoupdating results from CoreData then its best to use NSFetchedResultsController. Apple has sample code on how to do this here.
The sort version is you implement the delegate methods for willChangeContent and didChangeContent and forward the relevant changes (ie insert, delete and reload row) to the tableView, and this will keep your tableview in synch with your database.
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
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)
case .move:
break
case .update:
break
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
case .delete:
tableView.deleteRows(at: [indexPath!], with: .fade)
case .update:
tableView.reloadRows(at: [indexPath!], with: .fade)
case .move:
tableView.moveRow(at: indexPath!, to: newIndexPath!)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
Upvotes: 2