Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 425
MJQZ1347 Avatar asked Jul 06 '16 22:07

MJQZ1347


People also ask

Can static variables be accessed outside the class?

From outside the class, "static variables should be accessed by calling with class name." From the inside, the class qualification is inferred by the compiler.

Can we assign value to static variable in C#?

Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.

Can we change value of static variable?

Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods.

Do static variables keep their value?

A static variable has a property to retain its value from it's previous scope. This means that it's value does not get re-initialized if the function in which it is declared gets called multiple times.


1 Answers

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.

like image 88
OOPer Avatar answered Nov 05 '22 18:11

OOPer