LinkingObjects is one for many in Realm

I have a stop that has many destinations. I managed to do this using the linkingObjects function, but it has been deprecated since the last update, and I have to use the LinkingObjects object.

Stop

class Stop: Object { dynamic var name:String = "" var directions = List<Direction>() override static func primaryKey() -> String? { return "name" } } 

Old direction

 class Direction: Object { dynamic var tag:String = "" var stop:Stop? { return linkingObjects(Stop.self, forProperty: "directions").first } } 

When I apply my previous approach to a new object, I always get nil

New null direction returned by LinkingObjects

 class Direction: Object { dynamic var tag:String = "" let stop = LinkingObjects(fromType: Stop.self, property: "directions").first //always return nil } 

But here I get an array with one element. Therefore, it works as it should.

New null direction returned by LinkingObjects

 class Direction: Object { dynamic var tag:String = "" let stops = LinkingObjects(fromType: Stop.self, property: "directions") } 

Question

Is there any other way to use "LinkingObjects" and not this last example, because in each case "direction.stop.first? .Name" instead of "direction.stop? .Stop"?

Of course, I could use the 'direction' function, which would always select the first element in the 'stop', but maybe I don't need to.

UPDATE

Meanwhile, I use this. This is an ideal solution, but it works.

 private let stops:LinkingObjects<Stop> = LinkingObjects(fromType: Stop.self, property: "directions") var stop:Stop? { return self.stops.first } 
+5
source share
2 answers

The solution you came up with at the moment is the best you could do.

We discussed whether any other API should be provided for special backlinks, but since there is no way to ensure their multiplicity at the data storage level, this has not made sense. In addition, you still need a wrapper object so that we can distribute updates. For this reason, a single way to get value through LinkedObjects seemed to be so far.

+1
source

How about defining a relationship differently?

  • Specify user side connection
  • Make a request to getter on the "many" side:

Therefore, it should look like this:

 class Child: Object { dynamic var name:String = "" dynamic var parent:Parent? = nil } class Parent: Object { dynamic var name:String = "" var children:Results<Child>? { return realm?.objects(Child.self).filter(NSPredicate(format: "parent == %@", self)) } } 
0
source

All Articles