繁体   English   中英

如何删除PersistentStore并重新创建它以添加新数据?

[英]How to delete PersistentStore and recreate it to add new data?

我在应用程序中使用CoreData数据库。 我需要删除它(模型和所有数据),并在应用程序更新时重新创建它。

要删除它,我使用destroyPersistentStore函数。 但是删除后,我需要重新创建persistentStores ,以新数据填充它。

这是我的CoreDataManager类:

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)")
         }
  }
}

我的recreateCoreData调用发生错误,因为存储与创建时使用的存储不兼容。

怎么了?

编辑:

数据库模型在2个版本之间没有变化。

错误:

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

这可能是由于调用addPersistentStore时由于参数configurationName addPersistentStore

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

配置名称不是商店名称,如果从现有商店中转储配置名称,则会得到PF_DEFAULT_CONFIGURATION_NAME

您可以从现有商店( firstStore.configurationName )中使用它,或者通过再次调用persistentContainer.loadPersistentStores(...) firstStore.configurationName一点。

示例项目: https//github.com/ralfebert/CoreDataReset

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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