I am using NSFetchedResultsController
to display the already saved data in the tableView
. At the same time, I am checking for new data by a web service. When I receive data from the network, my database gets updated with the new data. The tableView
automatically gets updated. But the update in tableView
is not smooth. Please offer a suitable solution for swift 4
. Please watch this video which I have uploaded for the better explanation. https://www.youtube.com/watch?v=XhSEykQcP5A&feature=youtu.be
This is my NSFetchedResultsController
delegate implementation
extension CoreDataTableViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
let set = IndexSet(integer: sectionIndex)
switch (type) {
case .insert:
tableView.insertSections(set, with: .fade)
case .delete:
tableView.deleteSections(set, with: .fade)
default:
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.deleteRows(at: [indexPath!], with: .fade)
tableView.insertRows(at: [newIndexPath!], with: .fade)
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
I solved the issue.
Earlier, I was using saveContext
only once (after the for loop), after all the NSManagedObject
were generated. Now, I am using saveContext
after generating each NSManagedObject
. Below is the snippet of the code where I am creating the NSManagedObject
and saving them.
for z in 0...(json.count - 1) {
let a = json[z]["PackageName"].stringValue
let b = json[z]["ExamGroupId"].stringValue
let c = json[z]["TestList"].stringValue
let d = json[z]["TestPackageId"].stringValue
_ = TestPackage(packageNameCD: a, examGroupIdCD: b, testListCD: c, testPackageIdCD: d, context: self.fetchedResultsControler.managedObjectContext)
(UIApplication.shared.delegate as! AppDelegate).saveContext() // now I am saving here itself and not after the loop.
}
// (UIApplication.shared.delegate as! AppDelegate).saveContext() // earlier, I was saving here, after the for loop.
I have yet not fully understood it. But it does solve the problem. I will be very thankful to anyone who can explain it further.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments