Search code examples
iosswiftcocoa-touchkey-value-observingclass-variables

Observing a value of a static var in a class?


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'
}

What is a most elegant way of doing this?

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
    }
}

Solution

  • As for now, Swift cannot have observable class properties. (In fact, static properties are just global variables with its namespace confined in a class.)

    If you want to use KVO, create a shared instance (singleton class) which has online property and add observer to the instance.