领域不迁移

时间:2017-05-06 18:18:00

标签: ios swift3 realm

我在iOS-app中使用Realm(v2.7.0)。在第一次发布之后,我更改了一些我想要迁移的模型。

要执行此迁移,我已将此代码添加到application(application:didFinishLaunchingWithOptions:)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    Realm.Configuration.defaultConfiguration = Realm.Configuration(
        schemaVersion: 1,
        migrationBlock: { migration, oldSchemaVersion in
            if (oldSchemaVersion == 0) {
                // Changes for scheme v0 to v1
                print("Doing migration.")
                migration.enumerateObjects(ofType: Category.className()) { oldObject, newObject in
                    newObject!["id"] = String(describing: oldObject!["id"])
                }

                migration.enumerateObjects(ofType: Income.className()) { oldObject, newObject in
                    newObject!["id"] = String(describing: oldObject!["id"])
                }

                migration.enumerateObjects(ofType: Expense.className()) { oldObject, newObject in
                    newObject!["id"] = String(describing: oldObject!["id"])
                }

                migration.enumerateObjects(ofType: Debt.className()) { oldObject, newObject in
                    newObject!["id"] = String(describing: oldObject!["id"])
                }
            }
    })

    // Execute Migration
    let realm = try! Realm()

    return true
}

问题是这个代码块永远不会执行。我仍然得到错误:

fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors

当我在application(application:didFinishLaunchingWithOptions:)中放置一些断点时,它们永远不会到达。所以看起来在错误出现之前不会调用该方法。

怎么办?

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要使初始化延迟,然后控制器将等待直到完成迁移。如果不这样做,它将尝试在完成迁移之前进行初始化。问题在那里发生。

lazy var realm:Realm = {
    return try! Realm()
}()