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 是为了自动更新对象属性——这是错的吗?我是否缺少一些代码来完成这项工作?

这里有一个非常相似的问题(Swift 中的 Realm 迁移)(不是我!)但现在看起来已经过时了(当然我已经尝试了上面的解决方案!)

4

1 回答 1

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
于 2018-05-09T09:28:13.150 回答