我需要根据以下代码创建将discount:Double
更改为discounts:List<Discount>()
的迁移。
Realm Object
现在的外观。class Item:Object{
@objc dynamic var itemName:String = "Some Name"
@objc dynamic var discount:Double = 0 // need to change this property
}
这是我尝试进行更改的方式。
class Discount: Object {
@objc dynamic var name:String = "Discount Name"
@objc dynamic var discount:Double = 0.0
}
one-to-many
关系的修改对象。class Item:Object{
@objc dynamic var itemName:String = "Some Name"
let discounts = List<Discount>()
}
Realm.Configuration.defaultConfiguration = Realm.Configuration(
schemaVersion: 3,
migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < 3) {
migration.enumerateObjects(ofType: Item.className()) { oldObject, newObject in
let oldDiscount = oldObject!["discount"] as! Double
let discount = Discount()
discount.amount = oldDiscount
let discounts = newObject!["discounts"] as! List<Discount>
discounts.append(discount)
}
}
})
我遇到错误:
无法将类型为
RealmSwift.List<RealmSwift.DynamicObject>(0x1c8910068)
的值转换为RealmSwift.List<AppName.Discount> (0x1c890f6a0)
。
再次,问题是,如何创建将discount:Double
更改为discounts:List<Discount>()
的迁移?
您可以将折扣属性作为[oldDiscount]之类的列表迁移到新的折扣列表中>
这是代码。我重命名了一些对象,以使其更加清晰,因为重复使用“折扣”一词来引用该类,并且该属性令人困惑。
let vers = UInt64(1)
let config = Realm.Configuration( schemaVersion: vers, migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < vers) {
print("performing migration")
migration.enumerateObjects(ofType: ItemClass.className()) { oldItem, newItem in
let oldDiscount = oldItem!["discount"] as? Double ?? 0.0
let d = DiscountClass()
d.name = "Test"
d.discount = oldDiscount
newItem!["discountList"] = [d]
}
} else {
print("no migration needed")
}
})