Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add property observer to global variable inside class in Swift

I have a variable globalVariable declared at global scope that may change at any time.

Different ViewControllers in my app need to react differently, when globalVariable changes.

Thus it would be desirable to add a property observer in each ViewController that execute the needed code when globalVariable changes.

I cannot seem to achieve it with override or extension. What is the way to go here?

like image 438
Marmelador Avatar asked Oct 28 '25 09:10

Marmelador


1 Answers

If your goal is to simply know when your global variable changed, you could have it post a notification upon change:

extension NSNotification.Name {
    static let globalVariableChanged = NSNotification.Name(Bundle.main.bundleIdentifier! + ".globalVariable")
}

var globalVariable: Int = 0 {
    didSet {
        NotificationCenter.default.post(name: .globalVariableChanged, object: nil)
    }
}

Then any object can add an observer for that notification:

class ViewController: UIViewController {

    private var observer: NSObjectProtocol!

    override func viewDidLoad() {
        super.viewDidLoad()

        // add observer; make sure any `self` references are `weak` or `unowned`; obviously, if you don't reference `self`, that's not necessary

        observer = NotificationCenter.default.addObserver(forName: .globalVariableChanged, object: nil, queue: .main) { [weak self] notification in
            // do something with globalVariable here
        }
    }

    deinit {
        // remember to remove it when this object is deallocated

        NotificationCenter.default.removeObserver(observer)
    }

}

Note, this didSet mechanism will not detect changes if (a) the global variable is a reference type, i.e. a class; and (b) it merely mutates the object that the global variable references rather than replacing it with a new instance. To identify that scenario, you need to use KVO or other mechanism to detect mutation.

like image 80
Rob Avatar answered Oct 31 '25 01:10

Rob



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!