相关疑难解决方法(0)

在类中观察静态var的值?

我有一门课,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)

cocoa-touch key-value-observing class-variables ios swift

4
推荐指数
2
解决办法
1835
查看次数