在Realm Migration期间创建领域对象

时间:2015-11-08 02:10:54

标签: ios swift realm realm-migration

您是否可以在迁移期间创建领域对象?我想要提取现有领域对象的一部分并使用该数据创建一个新对象,但迁移总是挂起。这是我的迁移代码

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 个答案:

答案 0 :(得分:9)

您可以使用Migration.create(_:value:)在迁移期间创建对象。

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

它返回MigrationObject的实例。因此,您应该使用下标为其属性分配值。

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

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

newObject!["_date"] = newTransactionDate