vendredi 10 juin 2016

Single inverse relationship in Realm models


I'm developing a simple iOS app to learn Swift and I'm using Realm. As far as I know, in Realm inverse relationships are achieved with a LinkingObjects property which is a collection containing all objects linked to that one.

Consider this example from the Realm Documentation:

class Person: Object {
    // ... other property declarations
    let dogs = List<Dog>()
}

class Dog: Object {
    dynamic var name = ""
    dynamic var age = 0
    let owners = LinkingObjects(fromType: Person.self, property: "dogs")
}

In my model, I know that each Dog instance will only have one owner since every dog, when created is added to only one Person's List.

Now I'd like to have a owner: Person property in the Dog class that references to its only owner to make the code more intuitive and simpler (instead of having to write dog.owners.first every time) while keeping the lazy-loading behavior (they are lazily loaded, right?). I don't know how expensive it is to query the "Linking Objects", but since there will be many "Dogs" around, I think it would be better not to access them on object initialization.

For now these are the solutions I could think of:

1:

class Dog: Object {
    let owner: Person = LinkingObjects(fromType: Person.self, property: "dogs").first
}

2a:

class Dog: Object {
    private let owners = LinkingObjects(fromType: Person.self, property: "dogs")
    lazy var owner: Person = {return self.owners.first}()
}

2b:

class Dog: Object {
    lazy var owner: Person = {
        return LinkingObjects(fromType: Person.self, property: "dogs").first
    }()
}

3:

class Dog: Object {

    private let owners = LinkingObjects(fromType: Person.self, property: "dogs")
    var owner: Person {
        return self.owners.first
    }

}

I don't think "solution 1" is lazy loaded and, as in "solution 2", the owner won't be "auto-updating", however this shouldn't be a problem since in my case a Dog won't ever change owner.

What would you recommend to have a single inverse relationship in Swift?


Aucun commentaire:

Enregistrer un commentaire