混淆为什么Realm LinkingObjects()不起作用:(

时间:2016-12-09 15:54:12

标签: swift realm

我已经定义了两个非常基本的Object如下:

class Language: Object {
    dynamic var id: String = "" //"english", "chinese"
    let versions = List<Version>()

    convenience init(id: String, versions: [Version]) {
        self.init()
        self.id = id
        self.versions.append(objectsIn: versions)
    }

    override static func primaryKey() -> String? {
        return "id"
    }
}

class Version: Object {
    dynamic var id: String = "" //"kjv", "cus"
    dynamic var name: String = "" //"Union Simplified"
    let language = LinkingObjects(fromType: Language.self, property: "versions")

    convenience init(id: String, name: String) {
        self.init()
        self.id = id
        self.name = name
    }

    override static func primaryKey() -> String? {
        return "id"
    }
}

每个Language可以包含多个Version个,每个Version都有Language拥有它的引用(LinkingObject)。

接下来,我有以下代码:

    let kjvVersion = Version(id: "kjv", name: "King James Version")
    let englishLanguage = Language(id: "english", versions: [kjvVersion])
    print(kjvVersion)

检查kjvVersion.language会给我一个空的LinkingObject数组。为什么?!我在这里做错了什么?

1 个答案:

答案 0 :(得分:3)

LinkingObjects个对象包含Realm中链接到包含对象的对象。您的对象不是由Realm管理的,因此Realm中永远不会有任何链接到它们的对象。