Reputation: 3408
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.
Upvotes: 5
Views: 351
Reputation: 1352
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.
Upvotes: 3