Realm-cocoa: LinkingObjects(fromType: Class.self, property: "property") returns nil

Created on 4 May 2016  路  2Comments  路  Source: realm/realm-cocoa

When I try to access var inspection in "Code from version 0.100.0"
it returns nil

Code from version 0.100.0

class DLocation: DBase{
    dynamic var audioFile: String? = nil
    dynamic var imageFile: String? = nil

    let inspection = LinkingObjects(fromType: DInspection.self, property: "locations").first
 }

Code from v0.98

class DLocation: DBase{
    dynamic var audioFile: String? = nil
    dynamic var imageFile: String? = nil

        var inspection: DInspection!{
        return linkingObjects(DInspection.self, forProperty: "locations").first!
    }
}

When I use the code linkingObjects(DInspection.self, forProperty: "locations") I am getting desired results but XCode generates a warning "Deprecated".

But when I try to access variable inspection in the Code from version 0.100.0 LinkingObjects(fromType: DInspection.self, property: "locations")` the result is nil

Realm version: V (0.100.0)
Xcode version: V7.2
iOS/OSX version: OS X El Captain 10.11.4 (15E65)
Dependency manager + version: cocoapods v 0.39.0

T-Help

Most helpful comment

At present LinkingObjects can only be used to initialize a property of type LinkingObjects. In the code you've provided you're attempting to use it to compute a default value for a property of type DInspection. The LinkingObjects instance does not know which object it contains links to until after the Swift object's initializer has run, at which point inspection has already been initialized to nil.

The following will provide the same semantics that you had when using linkingObjects(_:forProperty:):

class DLocation: DBase{
    dynamic var audioFile: String? = nil
    dynamic var imageFile: String? = nil

    var inspection: DInspection { return inspections.first! }
    private let inspections = LinkingObjects(fromType: DInspection.self, property: "locations")
 }

All 2 comments

At present LinkingObjects can only be used to initialize a property of type LinkingObjects. In the code you've provided you're attempting to use it to compute a default value for a property of type DInspection. The LinkingObjects instance does not know which object it contains links to until after the Swift object's initializer has run, at which point inspection has already been initialized to nil.

The following will provide the same semantics that you had when using linkingObjects(_:forProperty:):

class DLocation: DBase{
    dynamic var audioFile: String? = nil
    dynamic var imageFile: String? = nil

    var inspection: DInspection { return inspections.first! }
    private let inspections = LinkingObjects(fromType: DInspection.self, property: "locations")
 }

Great! It worked. Thanks a lot for your time & support.

Was this page helpful?
0 / 5 - 0 ratings