Gerard Gerard - 2 years ago 360
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() = "Harry"
try! realm.write {

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

print( // -> result is nil

And also:

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

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

It seems that ownedDog is always
. Why could the inverse relation not be determined? Or should
always be of
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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download