Dudi Dudi - 5 months ago 36
iOS Question

LinkingObjects one to many in Realm

I have stop which have many directions. I've managed to do it using function 'linkingObjects' but since last update it's deprecated and I should use object 'LinkingObjects'.

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 new object then I always get
nil


New Direction with nil 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'm getting array with one element. So it works as it should.

New Direction with nil returned by LinkingObjects

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





Question

Is there other way to use 'LinkingObjects' rather than this last example because using in every time 'direction.stop.first?.name' instead of 'direction.stop?.stop'?

Of course, I could use in 'direction' function that will take always pick first element in 'stops' but maybe I don't have to.

UPDATE



In meanwhile I’m using this. This isn’t ideal solution, but works.

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

Answer

The solution you came up with yourself for now is the best what you could do.

We discussed whether we should expose any other API for singular backlinks, but as there is no way to enforce their multiplicity on the data storage layer, it didn't made sense so far. In addition, you would still need a wrapper object, so that we can propagate updates. For that reason a unified way to retrieve the value via LinkedObjects seemed to be the way so far.

Comments