I have the following realm model as below. The variants objects are in the product variants property, but when I try to access the product property from the variant it always returns 0 objects. I have already check the database and the relationship is there. (see attached screenshot)


public class Variant: Object {
public dynamic var id: String = NSUUID().UUIDString
public let product = LinkingObjects(fromType: Product.self, property: "variants").first
public override class func primaryKey() -> String { return "id" }
}
public final class Product: Object {
public dynamic var id: String = NSUUID().UUIDString
public dynamic var name: String = ""
public let variants = List<Variant>()
public override class func primaryKey() -> String { return "id" }
}
I am currently using realm version 1.0.0
Try:
private let products = LinkingObjects(fromType: Product.self, property: "variants")
public let product: Product? { return products.first }
This gives Realm Swift an opportunity to initialize the products property when your Variant instances are initialized. With the property declaration you posted Realm Swift has no way of determining which Variant the LinkingObjects instance is associated with before you call first on it.
Thanks @bdash! That works :-)
Most helpful comment
Try:
This gives Realm Swift an opportunity to initialize the
productsproperty when yourVariantinstances are initialized. With the property declaration you posted Realm Swift has no way of determining whichVarianttheLinkingObjectsinstance is associated with before you callfirston it.