是否可以在 Realm 迁移中重命名和更改属性的数据类型



我目前有一个属性为Double的对象,我想将其更改为doublesList

根据以下代码将price:Double更改为prices = List<Double>()的最佳方法是什么?

是否可以在 Realm 迁移中重命名和更改属性的数据类型?如果不是,在这种情况下,我是否需要将prices视为一个新属性并删除该属性price然后手动遍历 Realm 中的所有项目以进行更改?

迁移之前 - 我目前拥有的

class Item:Object{
@objc dynamic var itemName:String = "General"
@objc dynamic var price:Double = 0
}

迁移后 - 迁移后我想要什么

class Item:Object{
@objc dynamic var itemName:String = "General"
let prices = List<Double>()
}

迁移

以下迁移不起作用。如何修改它以使其工作?

/// Schema 1:
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
migration.renameProperty(onType: Item.className(), from: "price", to: "prices")
}
})

试试这个:

Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 1) {
migration.enumerateObjects(ofType: Person.className()) { oldObject, newObject in
// Append price value to new prices list
let price = oldObject!["price"] as! Double
newObject!["prices"] = [price]
}
}
})

最新更新