Adz Adz - 27 days ago 10
JSON Question

Realm Swift, relationship and memory space error

In my code, I have two class linked like this :

class parent: Object {
dynamic var id:Int = 0
let children = List<child>()
...
}

class child: Object {
dynamic var myParent = parent?
...
}


I have done that to be able to find easily the parent of a child and his children of a parent.
But now, when I want to get a Parent :

let myParent = realm.objects(parent).filter("id == 1").first


I get a very big JSON string in return. Because my parent have many children, and for each children I display the parent AND the children...So my json is nearly infinite.

Can this be the problem of my error "Cannot allocate memory size" ?
Would it be better to declare my child like this :

class child: Object {
dynamic var myParentId:Int = 0
...
}


I don't know if a very big json can be a reason for a memory space error.

I hope my questions is clear enough :)

Thanks for your help !

TiM TiM
Answer

While you can indeed manually manage the 2 relationships between a child and a parent, as you've discovered, it can be quite tricky.

Realm provides a support for inverse relationships where an object can look up which objects it belongs to.

class parent: Object {
    dynamic var id:Int = 0
    let children = List<child>()
    ...
}

class child: Object {
    let parent = LinkingObjects(fromType: parent.self, property: "children").first
    ...
}

That should hopefully automate what you're trying to do here. :)

Comments