Ios 向CoreData添加新版本

Ios 向CoreData添加新版本,ios,xcode,core-data,Ios,Xcode,Core Data,我有一个包含两个实体的coredata模型,一个实体与另一个实体有关系(DataSet---(对多个)-->DataPoints)。起初,我有一个反向关系,但我最终不需要它。我知道,如果我只是改变它,人们将不得不重新安装应用程序,删除他们的所有数据。因此,我查看了如何更改它,但仍然允许旧模型兼容 我遵循了我在上发现的以下步骤: 选择*.xcdatamodelId 选择编辑器>添加模型版本 提供基于先前模型的版本名称 确保选择了刚创建的新版本 给它一个新的标识符(在文件选择器中) 做些改变 选择*

我有一个包含两个实体的coredata模型,一个实体与另一个实体有关系(DataSet---(对多个)-->DataPoints)。起初,我有一个反向关系,但我最终不需要它。我知道,如果我只是改变它,人们将不得不重新安装应用程序,删除他们的所有数据。因此,我查看了如何更改它,但仍然允许旧模型兼容

我遵循了我在上发现的以下步骤:

  • 选择*.xcdatamodelId
  • 选择编辑器>添加模型版本
  • 提供基于先前模型的版本名称
  • 确保选择了刚创建的新版本
  • 给它一个新的标识符(在文件选择器中)
  • 做些改变
  • 选择*.xcdatamodelId并更改模型版本(在文件中) 选择器)
  • 我还选择了模型,并将“模型版本”更改为“*v2”

    但当我在旧型号的设备上运行应用程序时,只要它尝试创建数据,我就会得到错误:

    未解决的错误域=您的\u错误\u域代码=9999“未能 初始化应用程序保存的数据“ UserInfo={NSLocalizedDescription=未能初始化 应用程序保存的数据,NSUnderlyingError=0x1c06402d0{Error Domain=nscocaerorrordomain Code=134100“托管对象模型 用于打开持久存储的版本与当前版本不兼容 用于创建持久存储的。”


    我不确定我是否错过了什么或者我做错了什么。我唯一改变的是,这种关系不再有代码中甚至没有使用的反向关系。我从阅读资料中了解到的方式是,如果设备上没有最新的型号,它将寻找兼容的型号。

    当您设置持久存储公司时ordinator确保您指定希望它在设置时传递的选项字典中自动迁移数据(如果适用)

    大概是这样的:

        do {
            try self?.psc?.addPersistentStore(
                           ofType: NSSQLiteStoreType, 
                configurationName: nil, 
                               at: url, 
                          options: [
                                 NSMigratePersistentStoresAutomaticallyOption: true,
                                 NSInferMappingModelAutomaticallyOption: true
                            ])
            print("Core Data Store setup")
        } catch {
            print("Error migrating store: \(error)")
        }
    
    如果您正在为iOS 10+构建另一个选项,则可以使用NSPersistentContainer为您管理上下文、模型和持久存储协调器

    (我还没有尝试使用NSPersistentContainer进行迁移,但我想我会让您知道这些迁移,以防它为您简化工作)

    下面是一个使用NSPersistentContainer的核心数据堆栈示例,而不是使用带有持久存储协调器的旧样式,等等:

    import CoreData
    
    class CoreDataStack {
    
        // added in case you want to initialize the persistent container with a specific managed
        // object model via
        // let container = NSPersistentContainer.init(name: DataModel, managedObjectModel: managedObjectModel())
        internal func managedObjectModel() -> NSManagedObjectModel {
            let bundle = Bundle(for: AppDelegate.self)
            guard let url = bundle.url(forResource: "DataModel", withExtension: "momd") else {
                fatalError("Error loading model from bundle")
            }
            guard let mom = NSManagedObjectModel(contentsOf: url) else {
                fatalError("Error initializing mom from: \(url)")
            }
    
            return mom
        }
    
        internal lazy var persistentContainer: NSPersistentContainer = {
            let container = NSPersistentContainer(name: "DataModel")
            container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in
    
                /*
                 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.
                 */
                if let error = error {
                    print("CoreData:  error \(error), \(String(describing: error._userInfo))")
                }
            })
            return container
        }()
    
        func performUITask(_ block: @escaping (NSManagedObjectContext) -> Void) {
            persistentContainer.viewContext.perform {
                block(self.persistentContainer.viewContext)
            }
        }
    
        func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) {
            persistentContainer.performBackgroundTask(block)
        }
    
        // MARK: - Core Data Saving support
        func saveContext () {
            let context = persistentContainer.viewContext
            if context.hasChanges {
                do {
                    try context.save()
                } catch {
                    // 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.
                    let nserror = error as NSError
                    fatalError("CoreData: Unresolved error \(nserror), \(nserror.userInfo)")
                }
            }
        }
    }
    

    您确定轻量级迁移与您的更改兼容吗?。您没有指定在初始化持久性存储协调器时传递的选项。@particleman它没有明确说明轻量级迁移中是否允许将关系从“有”和“反向”更改为“无”。我不确定是什么原因您在第二部分中说。请阅读上面链接中的“使用选项词典请求自动迁移”一节,该链接涵盖了请求轻量级迁移。谢谢,我将对此进行演示添加以下“为我工作”选项:[NSMigratePersistentStoresAutomaticalyOption:true,NSInFermappingModelAutomaticalyOption:true])