RealmSwift:如何正确创建To-One关系?

时间:2016-07-24 22:02:18

标签: ios swift realm

我们假设我有:

class Dog: Object {
    dynamic var race = ""
    dynamic var name = ""

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

class Person: Object {
    dynamic var name = ""
    dynamic var address = ""
    dynamic var dog: Dog?

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

首先我创建一个Dog并保存它:

let dog = Dog()
dog.race = "Dalmatian"

try! realm.write {
    realm.add(dog, update: true)
}

现在我在另一个班级中创建一个Person。关于这种情况,文档还不太清楚。在创建关系之前,是否需要先保存Dog的更改?:

let person = Person()
person.name = "Jim"

// retrieve dog from realm: 

if let dog = realm.objectForPrimaryKey(Dog.self, key: "Dalmatian") {
    dog.name = "Rex" // Owner gives dog a new name

    // Question:
    // Saving changes to Rex: is this step neccessary?
    try! realm.write {
         realm.add(dog, update: true)
    }

    person.dog = dog
}

try! realm.write {
    realm.add(person, update: true)
}

2 个答案:

答案 0 :(得分:2)

不,它会导致崩溃

dog

如果您想更新name' if let dog = realm.objectForPrimaryKey(Dog.self, key: "Dalmatian") { try! realm.write({ dog.name = "Rex" }) person.dog = dog } ,请写如下:

bindValue

了解详情:Realm.io/updating-objects

答案 1 :(得分:0)

您可以将整个对象图设置为非托管对象,并通过一次调用将它们全部保留。因此,您不需要先保留Dog并再次检索它以便能够在关系中使用它。

let dog = Dog()
dog.race = "Dalmatian"

let person = Person()
person.name = "Jim"
person.dog = dog

try! realm.write {
    realm.add(person, update: true)
}