Realm-cocoa: LinkingObjects always return empty.

Created on 31 May 2016  路  3Comments  路  Source: realm/realm-cocoa

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)

screen shot 2016-05-31 at 2 27 47 pm
screen shot 2016-05-31 at 2 27 32 pm

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" }
}
T-Help

Most helpful comment

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.

All 3 comments

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 :-)

Was this page helpful?
0 / 5 - 0 ratings