Swift 4中的KVO侦听器问题 [英] KVO listener issues in Swift 4
问题描述
我正在使用ViewModel
类,并且想要设置观察者(如果对loginResponse
变量有任何更改).
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
}
}
查看控制器代码:
override func viewDidLoad() {
super.viewDidLoad()
_ = viewModel.observe(\ViewModel.loginResponse) { (model, changes) in
print(changes)
}
}
我想在Viewcontroller中收听对loginResponse
变量的任何更改,但是没有得到回调.我在这里做什么错了?
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?
推荐答案
.observe(_:options:changeHandler:)
函数返回一个NSKeyValueObservation
对象,该对象用于控制观察的生存期.当它初始化或无效时,观察将停止.
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.
由于您的视图控制器未保留对返回的观察"的引用,因此它在viewDidLoad
末尾超出范围,因此停止观察.
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.
要继续观察视图控制器的生命周期,请将返回的观察值存储在属性中.如果在此之前完成"观察,则可以在观察中调用invalidate
或将属性设置为nil
.
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
.
这篇关于Swift 4中的KVO侦听器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!