Realm: LinkingObjects(fromType: Class.self, property: “property”) returns nil

Realm is really simple and powerful tool for developers to deal with local database. I highly recommend to use realm. Let’s go directly to the problem guys.

Realm provides inverse relationship which is great to use. But you might get the issue while getting parent object using LinkingObjects class. Let me show you first how it is used.

Person class

class Person: Object {
    dynamic var name:String = ""
    var dogs = List<Dog>()

    override static func primaryKey() -> String? {
        return "name"
    }
}

Dog class

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

So, what might go wrong? If you go to realm official examples you will get similar example mentioned above. But why are you still getting the same issue? Ok, let me tell you what is going wrong.

There might be two reasons for this problems.

  • Make sure you have set primary key. In above example I have set primary key as name for class Person
  • In order to use LinkingObjects, you need to save Realm Object to local database first. If you are testing without storing objects to local database, you won’t be able to use LinkingObjects. So the solution is, first store them to local database and then try to use linking objects.

That’s all guys. Hope this was helpful. I was going through this issue and found out that the solution. Hope this helps you too. Let me know if there is any other issue other than this. I will be happy to help.

Thanks

Peace.

Leave a Reply

santoshm