我有一门课,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'
}
Run Code Online (Sandbox Code Playgroud)
最优雅的方法是什么?
更新。这是我的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)") …Run Code Online (Sandbox Code Playgroud)