我在我的应用程序中使用Core Data数据库。我需要删除它(模型和所有数据)并在更新应用程序时重新创建它。
要删除它,我使用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."
这可能是因为调用configurationName
时参数addPersistentStore
:
addPersistentStore(ofType: NSSQLiteStoreType, configurationName: storeName, ...)
配置名称不是商店名称,如果从现有商店转储它,则会得到PF_DEFAULT_CONFIGURATION_NAME
作为结果。
您可以通过再次调用firstStore.configurationName
从现有商店(persistentContainer.loadPersistentStores(...)
)中使用它,或者更容易使用imho。