在类中观察静态var的值? [英] Observing a value of a static var in a class?
问题描述
我有一个static var
的类,用于存储当前的在线连接状态.我想通过其他类观察ConnectionManager.online
的值.我想用 KVO 来做到这一点,但是将static
变量声明为dynamic
会导致错误:
I have a class with a static var
where the current online connection status is stored. I want to observe the value of ConnectionManager.online
through other classes. I wanted to do this with KVO, but declaring a static
variable as dynamic
causes an error:
class ConnectionManager: NSObject {
dynamic static var online = false
// adding 'dynamic' declaration causes error:
// "A declaration cannot be both 'final' and 'dynamic'
}
最优雅的方法是什么?
更新.这是我的KVO部分代码:
Update. This my code for the KVO part:
override func viewDidLoad() {
super.viewDidLoad()
ConnectionManager.addObserver(
self,
forKeyPath: "online",
options: NSKeyValueObservingOptions(),
context: nil
)
}
override func observeValueForKeyPath(keyPath: String?,
ofObject object: AnyObject?,
change: [String : AnyObject]?,
context: UnsafeMutablePointer<Void>) {
if keyPath == "online" {
print("online status changed to: \(ConnectionManager.online)")
// doesn't get printed on value changes
}
}
推荐答案
到目前为止,Swift无法具有可观察的类属性. (实际上,静态属性只是其名称空间限制在类中的全局变量.)
As for now, Swift cannot have observable class properties. (In fact, static properties are just global variables with its namespace confined in a class.)
如果要使用KVO,请创建一个具有online
属性的共享实例(单个类),并将观察者添加到该实例中.
If you want to use KVO, create a shared instance (singleton class) which has online
property and add observer to the instance.
这篇关于在类中观察静态var的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!