Realm迁移中将属性Double更改为List

问题描述 投票:0回答:1

我需要根据以下代码创建将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>()的迁移?

ios swift realm database-migration realm-migration
1个回答
1
投票

您可以将折扣属性作为[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")
    }
 })
© www.soinside.com 2019 - 2024. All rights reserved.