Hi all
I have a problem with core data, where when a new user login that is different from the previous user i delete all of core data by using "destroyPersistentStore".
Then i recreate the persistent store, this works when i am testing. When it does not work for one of my users when she test.
I am not sure why this should not work, i have added the code i use to destroy the persistent store below.
This code is run after login but before the view changes away from my login view.
// Retrieves the shared `AppDelegate` instance
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
appDelegate.destroyDataSyncBackground()
// Get a reference to a NSPersistentStoreCoordinator
let storeContainer =
appDelegate.persistentContainer.persistentStoreCoordinator
// Delete each existing persistent store
for store in storeContainer.persistentStores {
if let url = store.url {
do {
try storeContainer.destroyPersistentStore(
at: url,
ofType: store.type,
options: nil
)
} catch {
print("Failed to deleted all")
}
} else {
print("Failed to deleted all")
}
}
// Re-create the persistent container
appDelegate.persistentContainer = NSPersistentContainer(
name: "CueToCue" // the name of
// a .xcdatamodeld file
)
// Calling loadPersistentStores will re-create the
// persistent stores
appDelegate.persistentContainer.loadPersistentStores {
(store, error) in
// Handle errors
let description = NSPersistentStoreDescription()
description.shouldMigrateStoreAutomatically = true
description.shouldInferMappingModelAutomatically = true
appDelegate.persistentContainer.persistentStoreDescriptions = [description]
}
// Reapply context configuration
let viewContext = appDelegate.persistentContainer.viewContext
viewContext.automaticallyMergesChangesFromParent = true
viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
do {
try viewContext.save()
appDelegate.recreateDataSyncBackground()
} catch {
print("Debug: saving delete all failed.")
}
}
The function "destroyDataSyncBackground" just set the my sync class to nil so stop any changes to core data while the code is running.
The function "recreateDataSyncBackground" recreate the sync class so fetch, post and patch requests is made again.