I have a tableView which I populate with cells. The data is being fetched as json from a private api and stored as CoreData. As the cells are being reused I fetched their imageView via a delegate method (from web URL). The problem occurs when I try to save that image data into that managed object. So when the image data is fetched, I fetch the managedObject, add the image data and re-save it. However this has a tremendous impact on the tableview performance (lagging tableview scrolling). I tried fetching and saving in background (privateQueueConcurrencyType) but nothing changes. Any recommendation is greatly appreciated.
func updateCoreDataImage(image:Data, for Url:String) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let priMOC = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
priMOC.parent = context
priMOC.perform {
do{
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DB")
request.predicate = NSPredicate(format: "url = %@", Url)
request.includesSubentities = false
request.returnsObjectsAsFaults = false
let result = try? context.fetch(request)
let object = result![0] as! NSManagedObject
object.setValue(image, forKey: "image")
try priMOC.save()
print("save")
} catch {
print(error.localizedDescription)
}
}
}