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.

Dan
  • 303
  • 3
  • 15

1 Answers1

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
jpsim
  • 14,329
  • 6
  • 51
  • 68
Michael
  • 8,891
  • 3
  • 29
  • 42
  • 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. – Dan Nov 22 '16 at 14:03
  • 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). – jpsim Nov 23 '16 at 21:23
  • I've updated the answer to reflect this. It should be correct now. – jpsim Nov 23 '16 at 21:24