2

我已经成功启动了我的应用程序的第一个版本MyProject.xcdatamodel。现在我的第二个版本正在开发中,我创建了名为MyProject2.xcdatamodel基于的新模型版本MyProject.xcdatamodel并将其设置为Current. 我已启用轻量级迁移,如下所示AppDelegate

lazy var persistentContainer: NSPersistentContainer = {

let container = NSPersistentContainer(name: "MyProject")

    // Support for light-weight migration 
    /*-------------------------------------------------------*/
    let description = NSPersistentStoreDescription()
    description.shouldMigrateStoreAutomatically = true
    description.shouldInferMappingModelAutomatically = true
    container.persistentStoreDescriptions = [description]
    /*-------------------------------------------------------*/

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

这样做之后,我首先安装了我的旧版本,然后在旧版本之上安装了新版本。在启动新版本时,没有从我没有接触过的旧模型的数据库表之一中找到数据。如果我删除这 4 行迁移,它正在获取数据。

可能是什么原因?我为轻量级迁移做错了什么吗?

4

1 回答 1

1

您需要为实际模型的数据库位置指定 URL。

    lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: Constants.yourModelName)

    if let storeURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("\(Constants.yourModelName).sqlite") {
        /*add necessary support for migration*/
        let description = NSPersistentStoreDescription(url: storeURL)
        description.type = NSSQLiteStoreType
        description.shouldMigrateStoreAutomatically = true
        description.shouldInferMappingModelAutomatically = true
        container.persistentStoreDescriptions =  [description]
    }

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {
            print("Unresolved error, \((error as NSError).userInfo)")
        }
    })
    return container
}()
于 2021-11-04T07:33:23.127 回答