【发布时间】:2016-11-09 03:32:57
【问题描述】:
我有一个带有static var 的类,其中存储了当前的在线连接状态。我想通过其他类观察ConnectionManager.online的值。我想用 KVO 来做这件事,但是将 static 变量声明为 dynamic 会导致错误:
class ConnectionManager: NSObject {
dynamic static var online = false
// adding 'dynamic' declaration causes error:
// "A declaration cannot be both 'final' and 'dynamic'
}
这样做最优雅的方式是什么?
更新。这是我的 KVO 部分代码:
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
}
}
【问题讨论】:
标签: ios swift cocoa-touch key-value-observing class-variables