【发布时间】:2020-02-01 13:10:57
【问题描述】:
在将 XCode 更新到版本 11 后,我向 Core Data 添加了一个新模型版本,并在新版本中向实体添加了一个新属性。使新版本处于活动状态并将新属性添加到托管对象文件中。
向用户发布此版本后,它开始崩溃并显示以下消息:“用于打开持久存储的托管对象模型版本与用于创建持久存储的版本不兼容。”和“列名重复 ZNEWCOLUMN”。到目前为止,我对 Core Data 模型进行了很多更改,并且迁移始终有效。
此崩溃仅出现在 iOS 13 上!
这是我加载核心数据的方式:
lazy var managedObjectContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "MyModel")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
let description = NSPersistentStoreDescription()
description.shouldInferMappingModelAutomatically = true
description.shouldMigrateStoreAutomatically = true
container.persistentStoreDescriptions.append(description)
return container
}()
任何帮助将不胜感激。
【问题讨论】:
-
要添加新属性,您无需添加新模型版本,只需将属性添加到模型中,Core Data 将为您完成所有工作。
-
@Gigi 这可能是真的,我在添加属性时总是在创建一个新版本。但问题是:如何为已经更新应用的用户安全地解决这个问题?
-
这可能值得检查,如果我自己解决了这个问题,我会发布,但是当我实例化
NSPersistentContainer时,我总是在调用container.loadPersistentStores(:)之前先.append(description)。 -
@andrewbuilder 这可能是有道理的,在我在谷歌中找到的每个示例中,描述都是在加载之前设置的,如您所提到的。唯一有趣的问题是:迁移到现在是如何进行的?
-
这是一个有趣的问题。同样,我对此不确定——有人比我更熟悉 Core Data 的详细操作——我猜
container在lazy实例化和description应用后仍保留在内存中,尽管是在加载商店后发布,因此对persistentContainer的任何后续调用都可能触发迁移。我很感兴趣,会做更多的研究——如果我找到任何线索,我会告诉你的。
标签: ios swift core-data migration