5

Once I download data from server, I am trying to save data in Core Data. As per Apple documentation I am using parent-child context to perform save operation, as follow:

fileprivate func saveDataInLocalDataBase(_ mList: [Info]?) {

    if mList != nil {
        let mainContext = self.managedObjectContext
        let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        privateContext.parent = mainContext

        privateContext.perform {

            for mObj in mList! {
                let entity =  NSEntityDescription.entity(forEntityName: entityName, in:privateContext)
                let managedObj = NSManagedObject(entity: entity!, insertInto:privateContext) as! NSManagedObject

               mObj.populateFieldsForManagedObject(managedObj)
            }
            do {
                try privateContext.save()
                mainContext?.performAndWait {
                    do {
                        try mainContext?.save()
                    } catch {
                        fatalError("Failure to save context: \(error)")
                    }
                }
            } catch {
                fatalError("Failure to save context: \(error)")
            }
        }
    }
}

However, sometimes when I try to fetch data from core data it returns 0 objects. That means my data is not saving in Core Data. Can anyone know what is the problem, even though my service returns proper data.

Note: This issue occurs randomly.

Is it possible that when app tries to save data in background and user minimizes the app, so private context it unable to save data when app is in background?

Thanks in advance.

Nuzhat Zari
  • 3,398
  • 2
  • 24
  • 36
  • I can't seem to see anything off with your code, but is there any chance that `self.managedObjectContext` is `nil` in some situations? If so your attempts to save to the `mainContext` would fail, so perhaps that's where the issue is occurring? – BHendricks Apr 12 '18 at 14:15

1 Answers1

3

The answer to your question is no private has nothing to do with it. The data should still be saved in the background. You need to figure out the situation in which it is happening. Maybe the service stops running in the background as soon as you minimize the app.

Moaz Khan
  • 1,272
  • 1
  • 13
  • 28