During RealmSwift migration
, i want to migrate from dynamic var customObject: CustomObject
to let customObjectList = List<CustomObject>()
. CustomObject
is type of Object
This is the chunk of code within migration
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
Could not cast value of type 'RealmSwift.DynamicObject' (0x1015c82d0) to 'AppName.CustomObject' (0x1006e5550).
How do i achieve what i want? Currently what i can think of is to create a CustomObject & manually assign the values to it.
EDIT 1
I want to add a primaryKey to CustomObject. I keep getting duplicate primary key error, i'm pretty sure the key assigned is unique.
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=0 "Primary key property 'resultKey' has duplicate values after migration."
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)
}
EDIT 2
I manage to figure out what is the error by making
resultKey
not a primary key. The app runs perfectly and when i open.realm
to see the values, there are some fields with""
underresultKey
-> The duplicated primary key. ><