3

期间RealmSwift migration,我想从迁移dynamic var customObject: CustomObjectlet customObjectList = List<CustomObject>()CustomObject是类型Object

这是迁移中的代码块

let newList = List<CustomObject>()
if oldObject!["customObject"] != nil {

   print(oldObject!["customObject"])                  
   var obj = oldObject!["customObject"]
   var result: CustomObject = obj as! CustomObject //Crash
   farList.append(result)
}

newObject!["customObjectList"] = newList

无法将“RealmSwift.DynamicObject”(0x1015c82d0)类型的值转换为“AppName.CustomObject”(0x1006e5550)。

我如何实现我想要的?目前我能想到的是创建一个 CustomObject 并手动为其分配值。

编辑 1

我想向CustomObject 添加一个primaryKey。我不断收到重复的主键错误,我很确定分配的键是唯一的。

致命错误:“试试!” 表达式意外引发错误:错误域 = io.realm 代码 = 0“主键属性 'resultKey' 在迁移后具有重复值。”

 migration.deleteData(CustomObject.className())

 if oldObject!["customObject"] != nil {
          let oldSubFar = oldObject!["customObject"] as! MigrationObject
          var newFarDict = oldSubFar.dictionaryWithValuesForKeys(["firstName","secondName"])
          newFarDict["resultKey"] = NSUUID().UUIDString + "v1"


          let newSubFar = migration.create(CustomObject.className(), value: newFarDict )
          print(newSubFar) //its the updated object that i want
          let subFarList = newObject!["customObjectList"] as! List<MigrationObject>         

          subFarList.append(newSubFar)               

 }

编辑 2

resultKey我设法通过不设置主键来找出错误所在。该应用程序运行完美,当我打开.realm查看值时,有些字段""resultKey-> 重复的主键下。><

4

1 回答 1

6

我想你想做的是如下:

如果需要,请删除所有CustomObject数据,因为迁移列表对象无法附加现有对象。

然后您可以枚举User对象,并CustomObjectUser的属性中创建每个对象。并且新User对象具有customObject属性,然后将该对象附加CustomObject到列表中。

migration.deleteData(CustomObject.className()) // If needed

migration.enumerate(User.className()) { oldObject, newObject in
    if let oldObject = oldObject,
        let newObject = newObject {
            let oldCustomObject = oldObject["customObject"] as! MigrationObject
            let newCustomObject = migration.create(CustomObject.className(), value: oldCustomObject)

            let customObjectList = newObject["customObjectList"] as! List<MigrationObject>
            customObjectList.append(newCustomObject)
    }
}
于 2015-10-26T08:55:46.947 回答