harsh_v
harsh_v

Reputation: 3269

RealmSwift LinkingObjects(fromType: Class.self, property: "property") return nil

When I try to access var `inspection` in code block "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!
    }
}


class DBase: Object{
    dynamic var id:Int = 0
    dynamic var serverId: String! = "-1"
    dynamic var updatedAt: NSDate = NSDate()
}

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

Question

Should I stick with the deprecated code? or I am doing something wrong here?

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

Upvotes: 0

Views: 464

Answers (1)

harsh_v
harsh_v

Reputation: 3269

Realm support on Github provided me with this solution.

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.

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")
 }

Upvotes: 1

Related Questions