Data in persistent store disappears after app restarting

I have main context in controller:

let mainContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext


Then I create private context in my operation with passing reference to mainContext:

privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.parentContext = self.mainContext

privateContext.performBlock {
  let someObj = NSEntityDescription.insertNewObjectForEntityForName(SomeObj.entityName, inManagedObjectContext: privateContext) as! SomeObj
  someObj.prop1 = "some1"
  someObj.prop2 = "some2"
  ...

  if privateContext.hasChanges {
    do {
      try privateContext.save()
    }
    catch let saveError as NSError {
      finishWithError(saveError)
    }
  }
}


And then I get saved items from my controller:

var someObjArr = [SomeObj]()
let mainContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
      
let someObjRequest = NSFetchRequest(entityName: SomeObj.entityName)
do {
  someObjArr = try mainContext.executeFetchRequest(someObjRequest) as! [SomeObj]
  print(someObjArr)
} catch {
  print(error)
}


And this works - I have array of SomeObj from data store.

But if I restart application and try to get this array without presaving data I have empty array.

Why so? What's wrong in my steps? Why does data disappear after application restart being saved before.

The code you show only saves the private context, which saves those changes into the main context. You still need to save the main context at some point.

Thank you!


That's right. I added the line with saving to main context and now it works:

...
try privateContext.save()
try privateContext.parentContext?.save() // This line was added to previous code
...
Data in persistent store disappears after app restarting
 
 
Q