0

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)
        }
    }
}
Witek Bobrowski
  • 3,749
  • 1
  • 20
  • 34
snksnk
  • 1,566
  • 4
  • 21
  • 46
  • CoreData is not designed for storing large files (or any files) like images. You should store the image in the Documents directory and save the URL only to the CoreData – Witek Bobrowski Jan 16 '21 at 18:21
  • @witekbobrowski its just a small thumbnail.. nothing more than just a few KB.. Thats why I thought of saving it along side other info.. Nevertheless, you think storing to Doc Dir is my only option? – snksnk Jan 16 '21 at 18:34
  • 1
    I would avoid storing images or other assets like audio in CoreData at all cost, even if it is just a few KB. The larger your CoreData becomes, the slower it gets so you are potentially introducing performance problems that can surface at some point. File system is already a great data base for large files, with even better features then CoreData. For example, you can save those thumbnails into the Temp folder so OS can purge them when it runs out of space. – Witek Bobrowski Jan 16 '21 at 18:52
  • 1
    Check out this thread: https://stackoverflow.com/a/4158322/8160613 – Witek Bobrowski Jan 16 '21 at 18:53

0 Answers0