Inline KVO of a Property in another view controller

…衆ロ難τιáo~ 提交于 2019-12-02 06:05:24

The observer is destroyed because there is no reference to it after the other view controller has been presented. You have to store it

observer = vc.observe(\.value) { ... }

where observer is a property of the calling view controller.

A self-contained command-line project example: This prints "new string" as expected:

class A: NSObject {
    @objc dynamic var value: String = ""
}

let a = A()
let observer = a.observe(\.value) { (_, _) in print("new string") } // (*)
a.value = "Hello world"

But nothing is printed if (*) is replaced by

_ = a.observe(\.value) { (_, _) in print("new string") }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!