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

标签 ios swift core-data nspersistentstore

我在我的应用程序中使用了 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 调用出错,因为存储与创建时使用的存储不兼容。

怎么了?

编辑:

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

错误:

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(ofType: NSSQLiteStoreType, configurationName: storeName, ...)

配置名称不是商店名称,如果您从现有商店转储它,您将得到 PF_DEFAULT_CONFIGURATION_NAME 作为结果。

您可以从现有商店 (firstStore.configurationName) 中使用它,或者恕我直言,通过再次调用 persistentContainer.loadPersistentStores(...) 更容易一些。

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

关于ios - 如何删除 PersistentStore 并重新创建它以添加新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162140/

相关文章:

iphone - 使用关系从一对多变为一对一的实体迁移核心数据存储时出现 NSInferredMapping 模型错误

ios - 以编程方式调用时,自定义 xib View 不会明显显示

ios - JSON 错误 : NSInvalidArgumentException reason Invalid top-level type in JSON write in Swift3 iOS

IOS - 当应用程序在后台从 UNNotificationAction 触发后发送 http 请求

ios - iPhone:定期收听 GPS 和电池耗尽

ios - Core Data addPersistentStoreWithType 返回 nil,但错误也是 nil

iphone - Core Data 最大存储空间 iPhone

ios - 为什么要为即将推出的 iPhone 6 的大屏幕使用 Storyboard?不同之处?

ios - 在 VLC 媒体播放器中缓存

ios - 如何在 Swift 中处理返回纯文本的 API,每行一个单词?