Gerard Gerard - 5 months ago 167
Swift Question

How to determine an inverse relationship of a to-one relationship using Realm?

Is it possible in Realm to obtain the inverse relation of a to-one relationship?

For example:

class Dog: Object {
dynamic var name: String?
dynamic var owner: Person?
}

class Person: Object {
dynamic var name: String?
let dog = LinkingObjects(fromType: Dog.self, property: "owner").first
}



let person = Person()
person.name = "Harry"
try! realm.write {
realm.add(person)
}


let dog = Dog()
dog.name = "Fido"
dog.owner = person
try! realm.write {
realm.add(dog)
}


print(person.dog?.name) // -> result is nil


And also:

let arbitraryPerson = realm.objects(Person).filter("name contains 'Harry'").first!
let dogOwned = arbitraryPerson.dog

print(dogOwned?.name) // -> result is nil


It seems that ownedDog is always
nil
. Why could the inverse relation not be determined? Or should
dog
always be of
list<T>
type (i.e. to-many relationship) to force a relation between these objects? In this situation I get it working, but it feels not correct to force a to-many relationship when it isn't.

Answer

As far as I understand it, relations in Realm are not bi-directional by default, as you might be used to from Core Data. So if you want both objects to know of the relation, you have to set it both ways;

dog.owner = person
person.ownedDog = dog
Comments