我有一个静态var类,其中存储当前的在线连接状态。我想通过其他课程观察ConnectionManager.online
的价值。我想与KVO
要做到这一点,但在宣布一个static
变量作为dynamic
导致错误:观察类中静态var的值?
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
}
}
谢谢,会尝试单身模式。 – MJQZ1347