2015-11-08 177 views
2

您是否能夠在遷移過程中創建領域對象?我想要提取現有領域對象的一部分並使用該數據創建一個新對象,但遷移總是會掛起。這是我的遷移代碼在領域遷移過程中創建領域對象

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 
      }) 
     } 
    } 
} 

回答

4

您可以使用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