本地域迁移无法正常工作Swift

时间:2018-05-09 09:04:52

标签: ios swift realm swift4 swift4.1

我不知道我在这里是否遗漏了什么。

在更新属性后运行我的应用程序而没有迁移块后出现崩溃(与此处Realm Migration not working相同的问题)

但是现在当我运行应用程序时,它必须运行迁移,因为它不再崩溃,但我的对象属性没有更新。

我更新了以下对象(“minReps”是我添加的对象):

class ExerciseGeneratorObject: Object {
    @objc dynamic var name = ""
    @objc dynamic var minReps = 0
    @objc dynamic var maxReps = 0

    convenience init(name: String, minReps: Int, maxReps: Int) {
        self.init()
        self.name = name
        self.minReps = minReps
        self.maxReps = maxReps
    }

然后我在appDelegate中运行这样一个空的迁移块:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let config = Realm.Configuration(

        schemaVersion: 3,

        migrationBlock: { migration, oldSchemaVersion in

            if (oldSchemaVersion < 3) {

            }
    })

    Realm.Configuration.defaultConfiguration = config

    let realm = try! Realm()

我认为Realm是为了在运行空迁移块时自动更新对象属性 - 这是错误的吗?我错过了一些代码来使这项工作吗?

这里有一个非常类似的问题(Realm migrations in Swift)(不是我!)但现在看起来已经过时了(我确定我已经尝试过上面的解决方案!)

1 个答案:

答案 0 :(得分:4)

当前的模式版本应该通过领域配置在应用程序中设置,你应该增加它,在你的代码中你将模式版本设置为3,并且如果oldSchemaVersion小于3,则要求领域迁移领域,将模式版本设置为4,它会起作用

    var config = Realm.Configuration(

        // Set the new schema version. This must be greater than the previously used
        // version (if you've never set a schema version before, the version is 0).

        schemaVersion: 4,

        // Set the block which will be called automatically when opening a Realm with
        // a schema version lower than the one set above

        migrationBlock: { migration, oldSchemaVersion in

            // We haven’t migrated anything yet, so oldSchemaVersion == 0

            if (oldSchemaVersion < 3) {
                // Nothing to do!
                // Realm will automatically detect new properties and removed properties
                // And will update the schema on disk automatically
            }
    })

    Realm.Configuration.defaultConfiguration = config
    config = Realm.Configuration()
    config.deleteRealmIfMigrationNeeded = true