如何将List更新为Realm中另一个Object中的参数

时间:2016-07-24 18:13:55

标签: ios swift arraylist realm

我有两个类,其中一个作为第二类的变量。它看起来像是:

class Dogs: Object {
    dynamic var name: String?
    dynamic var age: String?
}

class Person: Object {
    dynamic var owner: String?
    var dogs: List<Dogs>() //I would like to UPDATE one of element from this list
}

现在,我想更新此List<Dogs>中的一个元素,但我仍然遇到问题。我努力实现目标:

class ViewController: UIViewController {

    var person: Person?
    ...

    func update(){
        let updatedDog = Dogs()
        updatedDog.name = "Tinky"
        updatedDog.age = "12"
        try! realm.write {
        person.dogs[0] =  updatedDog
        }
    }
}

这个解决方案不起作用。你知道我怎么更新它?

1 个答案:

答案 0 :(得分:1)

ViewController中,您需要抓住实际的狗,然后更新并在写入区块中更新。

Realm().write {
   updatingDog.name = "Tinky"
   updatingDog.age = 12
}
// use `updatingDog` as normal

https://realm.io/docs/swift/latest/#updating-objects