How to delete PersistentStore and recreate it to add new data?

1.7k views Asked by At

I use a CoreData database in my app. I need to delete it (model and all data) and recreate it when the app is updated.

To delete it, I use destroyPersistentStore function. But after deleting, I need to recreate the persistentStores, to fill it with new data.

Here my CoreDataManager class:

class CoreDataManager {

    static let sharedManager = CoreDataManager()
    private init() {}

    lazy var persistentContainer: NSPersistentContainer = {

        let container = NSPersistentContainer(name: storeName)
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in

            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

   func resetCoreData(){

        guard let firstStoreURL = self.persistentContainer.persistentStoreCoordinator.persistentStores.first?.url else {
            print("Missing first store URL - could not destroy")
            return
        }

        do {
            try self.persistentContainer.persistentStoreCoordinator.destroyPersistentStore(at: firstStoreURL, ofType: NSSQLiteStoreType, options: nil)
        } catch  {
            print("Unable to destroy persistent store: \(error) - \(error.localizedDescription)")
        }
   }

 func recreateCoreData() {
        do {
             try self.persistentContainer.persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: storeName, at: firstStoreURL, options: nil)
         } catch {
             print("Unable to create persistent store: \(error) - \(error.localizedDescription)")
         }
  }
}

I have an error with my recreateCoreData call because the store is incompatible with the one used when it was created.

What's wrong?

EDIT:

The database model didn't change between 2 versions.

The error:

Error Domain=NSCocoaErrorDomain Code=134020 "The model configuration used to open the store is incompatible with the one that was used to create the store."
1

There are 1 answers

0
Ralf Ebert On

This probably happens because of the parameter configurationName when calling addPersistentStore:

addPersistentStore(ofType: NSSQLiteStoreType, configurationName: storeName, ...)

The configuration name is not the store name, if you dump it from the existing store, you get PF_DEFAULT_CONFIGURATION_NAME as result.

You could use this from the existing store (firstStore.configurationName), or imho a bit easier, by calling persistentContainer.loadPersistentStores(...) again.

Example project: https://github.com/ralfebert/CoreDataReset