Create a realm object during a Realm Migration

末鹿安然 提交于 2019-12-22 05:59:07

问题


Are you able to create a realm Object during a migration? I am wanting to extract part of an existing realm object and create a new object with that data, but the migration always hangs up. Here is my migration code

private class var migrationBlock: MigrationBlock {
    return { migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {
            print("Shema Version 0")
            migration.enumerate(Transaction.className(), { (oldObject, newObject) -> Void in
                let oldDate = oldObject!["date"] as! NSDate
                let newTransactionDate = TransactionDate()
                newTransactionDate.date = oldDate
                try! Realm.getRealm().write { Realm.getRealm().add(newTransactionDate, update: true) }
                newObject!["_date"] = newTransactionDate
            })
        }
    }
}

回答1:


You can use Migration.create(_:value:) to create object during migration.

https://realm.io/docs/swift/latest/api/Classes/Migration.html#/s:FC10RealmSwift9Migration6createFS0_FTSS5valuePSs9AnyObject__CS_13DynamicObject

It returns MigrationObject's instance. So you should use subscripting to assign a value to its property.

let oldDate = oldObject!["date"] as! NSDate

let newTransactionDate = migration.create(TransactionDate.className())
newTransactionDate["date"] = oldDate

newObject!["_date"] = newTransactionDate


来源:https://stackoverflow.com/questions/33589984/create-a-realm-object-during-a-realm-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!