Realm: LinkingObjects(fromType: Class.self, property: “property”) returns nil [Updated]
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() 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 three (updated @ March 1, 2020) reasons for this problems.
class Dog: Object {
dynamic var tag:String = ""
var owners: [Person] { return _owners }
private let _owners = LinkingObjects(fromType: Person.self, property: "dogs")
}
In above Dog
class, I have added new variable as owners
and made _owners
property private. Now, if you use this approach, the owners
variable wont return nil
this time. Did you see the object now? Well, I think it should return the value now.
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.