KVO listener issues in Swift 4

回眸只為那壹抹淺笑 提交于 2019-12-12 16:28:56

问题


I am using ViewModel class and want to setup observer if any changes into loginResponse variable.

@objcMembers class ViewModel: NSObject {

    var count = 300
    @objc dynamic var loginResponse :String

    override init() {
        loginResponse = "1"
        super.init()
        setupTimer()
    }

    func setupTimer(){
        _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(callTimer), userInfo: nil, repeats: true)
    }

    func callTimer(){
        let minutes = String(count / 60)
        let seconds = String(count % 60)
        loginResponse = minutes + ":" + seconds
        count =  count - 1
    }
}

View controller code:

override func viewDidLoad() {
    super.viewDidLoad()

    _ = viewModel.observe(\ViewModel.loginResponse) { (model, changes) in
        print(changes)
    }
}

I want to listen to any change into loginResponse variable in my Viewcontroller but it's not getting the callback. What am I doing wrong here?


回答1:


The .observe(_:options:changeHandler:) function returns a NSKeyValueObservation object that is used to control the lifetime of the observation. When it is deinited or invalidated, the observation will stop.

Since your view controller doesn't keep a reference to the returned "observation" it goes out of scope at the end of viewDidLoad and thus stops observing.

To continue observing for the lifetime of the view controller, store the returned observation in a property. If you're "done" observing before that, you can call invalidate on the observation or set the property to nil.



来源:https://stackoverflow.com/questions/50186963/kvo-listener-issues-in-swift-4

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