Daniel Daniel - 2 months ago 32
iOS Question

How to migrate old properties into a new object with Realm Swift

Previously, I had only one object that had every value that I needed. I "regrouped" them and made separate objects. I added properties with the type of the new objects to the original object.
How can I assign the old property values to the object's properties?

Here's the code for my objects:

class MainObject: Object {
dynamic var id: Int = 0
// Schema 0
dynamic var otherId: Int = 0
dynamic var otherStr: String = ""

dynamic var anotherId: Int = 0
dynamic var anotherD: Double = 0.0
dynamic var anotherText: String = ""

// Schema 1
dynamic var otherObjectVar: OtherObject?
dynamic var anotherObjectVar: AnotherObject?

// Schema 1
class OtherObject: Object {
dynamic var id: Int = 0
dynamic var str: String = 0
class AnotherObject: Object {
dynamic var id: Int = 0
dynamic var d: Double = 0.0
dynamic var text: String = ""

(Changed variable names)

I tried to use
convenience init(){}
but it didn't work. I also tried to assign an object instance to the newObject, but that didn't work either.
Here's that code for easier understanding:

let other = OtherObject()
other.id = 0
other.str = oldObject["otherStr"] as! string
newObject["otherObjectVar"] = other

How can I migrate the old properties into a new property which is another object?

EDIT: Temporarily, I solved it with

let obj = migration.create(MainObject.className())

but I don't think this is the right solution. So if anyone has a solution for this, I'd appreciate it.


Assuming you're doing this during schema migration, you need to use migration.create to create new objects, not their init. Then you would set them on the new object, along the lines of:

let other = migration.create(OtherObject.className())
other["id"] = 0
other["str"] = oldObject["otherStr"] as! String
newObject?["otherObjectVar"] = other