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
resultKeynot a primary key. The app runs perfectly and when i open.realmto see the values, there are some fields with""underresultKey-> The duplicated primary key. ><
I think what you'd like to do is like following:
Delete all CustomObject data if needed, because Migration List object cannot append existing objects.
Then you can enumerate User objects, and create each CustomObject from User's property. And new User object has customObject property, then append the CustomObject object to the list.
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With