ios - 具有非标准化数据的 Realm 迁移

标签 ios swift realm

假设您有一个 Realm 对象,例如

class Person: Object {
    var dynamic firstName: String = ""
    var dynamic lastName: String = ""
}

现在,我想升级数据库并将姓氏提取到一个像这样的新类中

class LastName: Object {
    var dynamic sirName: String = ""

    override public class func primaryKey() -> String {
        return "sirName"
    }
}

class Person: Object {
    var dynamic firstName: String = ""
    var dynamic lastName: LastName!
}

迁移会是什么样子?我尝试过简单的迁移,但这可能会导致多个 LastName 对象具有相同的 PrimaryKey。

最佳答案

在您的AppDelegatedidFinishLaunchingWithOptions中:

let configuration = Realm.Configuration(
    schemaVersion: 1, //This must be larger than the previous schemaVersion
    migrationBlock: { migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {
            migration.enumerate(Person.className()) { oldObject, newObject in
                let lastName = oldObject!["lastName"] as! String
                let newValue: [String: String] = ["sirName": lastName]
                let createdObject = migration.create(LastName.className(), value: newValue)
                newObject!["lastName"] = createdObject
            }
        }
})

Realm.Configuration.defaultConfiguration = configuration // Set the new configuration as default

let realm = try! Realm() // Open the default realm to perform the migration

要补充的是,现在这也适用于 primaryKey ,模型如下所示:

class Person: Object {
    dynamic var firstName: String = ""
    dynamic var lastName: LastName!
}

class LastName: Object {
    dynamic var sirName: String = ""

    override static func primaryKey() -> String? {
        return "sirName"
    }
}

但是,如果 lastName 存在重复项,则此迁移将不起作用,因为 primaryKey 是每个对象的唯一标识符,因此您应该确保有永远不会重复,请为 primaryKey 使用另一个属性,或者在 LastName 对象中根本不使用 primaryKey

关于ios - 具有非标准化数据的 Realm 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254369/

相关文章:

javascript - 如何检查结果是否为 __NSCFNumber?

ios - 如何在自定义 UIView 中连接 UICollectionView - Swift

android - 我应该使用 copyFromRealm() 来填充微调器吗?

ios - Realm swift : how to catch RLMException?

iphone - 对齐图标 TabBar

iOS 蓝牙 UUID 在 8.2 上启动一些应用程序后发生变化

ios - 如何在 Swift 中加载初始 View Controller ?

javascript - Realm-js 和 Node.js : exception during login to Realm Object Server

ios - AVAssetWriter:如何多次写入单个文件

swift - 创建加载图像/事件指示器,直到图像快速显示在屏幕上