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

时间:2016-05-04 13:11:07

标签: ios realm

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

版本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
 }
  

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

当我使用代码linkingObjects(DInspection.self, forProperty: "locations")时,我得到了理想的结果,但是XCode会生成警告"已弃用"。

  

问题

我应该坚持使用已弃用的代码吗?或者我在这里做错了什么?

领域版本:V(0.100.0)

Xcode版本:V7.2

iOS / OSX版本:OS X El Captain 10.11.4(15E65)

依赖管理器+版本:cocoapods v 0.39.0

1 个答案:

答案 0 :(得分:1)

Github上的Realm支持为我提供了这个解决方案。

目前,LinkingObjects只能用于初始化LinkingObjects类型的属性。在您提供的代码中,您尝试使用它来计算DInspection类型属性的默认值。在Swift对象的初始化程序运行之后,LinkingObjects实例不知道它包含哪个对象链接,此时检查已经初始化为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")
 }