Inline KVO of a Property in another view controller

怎甘沉沦 提交于 2019-12-02 13:48:01

问题


I have a vc with a dynamic var "value" and i need to know when it's changed in a closure in the calling cv.

target vc:

@objc dynamic var value: String = ""

source:

if let vc: TagButtonPopupViewController = sb.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("TagPopupViewController")) as? TagButtonPopupViewController {
        // configure vc
        vc.value = sender.title

        // observe
        _ = vc.observe(\.value) { (tbvc, change) in
            print("new string")
        }

        // present popup
        presentViewController(vc, asPopoverRelativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.maxY, behavior: NSPopover.Behavior.transient)
    }

but "observe" is never called. Any Ideas how to get notified in a closure whenever "value" has changed in Swift4?


回答1:


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


来源:https://stackoverflow.com/questions/45265586/inline-kvo-of-a-property-in-another-view-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!