I have added a Today Extension in my existing app and setup a separate core data stack(reusing the same code which is used to setup core data for the main app).
My app data gets deleted when I run the Today extension as if setting up of Today core data stack deletes the existing data. Refer below code for returning persistentCoordinator
:
let options = [NSMigratePersistentStoresAutomaticallyOption:true,
NSInferMappingModelAutomaticallyOption:true,
NSSQLitePragmasOption:["journal_mode":"MEMORY"]]
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: options, error: &error) == nil {
NSLog("Unresolved error \(error)")
}
return coordinator
After lots of debugging, and reading googled blogs and docs, I think the issue was because of mergedModelFromBundles
method of NSManagedObjectModel
.
I had multiple .xcdatamodels in my bundle and during set up of core data stack, I was using the above method to merge a single model.
As core data stack set up for Today, the model returned from the method was different than the one used by Main app to create sqlite store and hence the persistent store returned was different and needed migration.
But migration more often than not was failing and deleting my .sqlite(set up by main app) and was setting up a new sqlite.
One solution I found was to use
NSManagedObjectModel(contentsOfURL: modelPathURL!)
method to get managed object model, where url is the path url of momd file in bundle.
Refer: Core Data Migration Guide
However, I have not yet figured, how to give path url of three different xcdatamodelids as single path url and how to migrate them if in future any xcdatamodel changes.
So, at present I have merged three xcdatamodels into single xcdatamodel in my bundle to solve this issue.