Xcode 9 中的 Swift 4 - 如何轻量级核心数据迁移?

clo*_*xnu 1 xcode core-data swift swift4 ios11

我的核心数据将再更新一个属性,为了避免崩溃,我首先添加了一个新的模型版本,此外:

关于这个问题的大部分关键是改变:

coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
Run Code Online (Sandbox Code Playgroud)

选项:在代码中为零

options:[NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption: true]
Run Code Online (Sandbox Code Playgroud)

但是在我的appdelegate.swift 中,我找不到任何“persistentStoreCoordinator”,那么我可以在我的版本中迁移 CoreData 吗?

Gul*_*mar 6

You can achieve like this:

let container = NSPersistentContainer(name: "YourDbModelName")
let description = NSPersistentStoreDescription() 
description.shouldMigrateStoreAutomatically = true 
description.shouldInferMappingModelAutomatically = true 
container.persistentStoreDescriptions = [description]
Run Code Online (Sandbox Code Playgroud)


小智 5

Gulshan Kumar 的解决方案很好。就我而言,它不起作用,因为容器已经有一个描述对象,并​​且设置

container.persistentStoreDescriptions = [description]
Run Code Online (Sandbox Code Playgroud)

有效地删除了该对象,结果模型没有加载。我用了

container.persistentStoreDescriptions.append(description)
Run Code Online (Sandbox Code Playgroud)