简体   繁体   中英

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

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."

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM