【问题标题】:Did Realm support model version?Realm 是否支持模型版本?
【发布时间】:2016-03-29 08:19:42
【问题描述】:

我开始使用 Realm,但我没有找到任何关于如何处理模型版本的信息。例如,我想在我的应用程序的下一个版本中添加/删除一些属性。非常感谢提前!

【问题讨论】:

    标签: ios objective-c database swift realm


    【解决方案1】:

    这是领域关于迁移的文档页面:https://realm.io/docs/swift/latest/#migrations

    如果您在 Realm.Configuration 中指定更高的架构版本号,将自动迁移已删除和添加的属性。如果你想进行真正的迁移,你只需要使用迁移块,比如将一个属性映射到另一个。

    let realmConfiguration = Realm.Configuration(
        path: nil,
        inMemoryIdentifier: nil,
        encryptionKey: nil,
        readOnly: false,
        schemaVersion: schemaVersionNumber,
        migrationBlock: migrationBlock,
        objectTypes: nil)
    
    do {
        realm = try Realm(configuration: realmConfiguration)
        print("[REALM] Path: \(realm.path)")
    } catch let error as NSError {
        fatalError("Error opening realm: \(error)")
    }
    

    【讨论】: