0

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())
migration.delete(obj)

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

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

Yes, I'm doing it the schema migration. I tried your answer, but I get this error: Value of type 'MigrationObject' (aka 'DynamicObject') has no member 'id'The object has an id field, so it shouldn't show an error.
This should actually be other["id"] and other["str"]. The reason you're getting that error message @Daniel is that Realm objects in a migration block aren't your typed models (that obviously wouldn't work when dealing with objects from older schema versions, whose typed models are no longer around).
I've updated the answer to reflect this. It should be correct now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.