2

How should I properly set up to receive notifications when the variable changes on the shared instance of the singleton? Currently, the block is never fired.

class MyViewController: UIViewController {
    private var observer: NSKeyValueObservation?

    func configureKVO() {
        observer = MySingleton.shared.observe(\.shouldFetchDataFromServer) { (manager, change) in
            print("Changed: \(manager.shouldFetchDataFromServer)")
        }
        MySingleton.shared.shouldFetchDataFromServer = false
        MySingleton.shared.shouldFetchDataFromServer = true
    }
}

class MySingleton: NSObject {
    static let shared = MySingleton()
    @objc var shouldFetchDataFromServer: Bool = false
}
subjective_c
  • 282
  • 2
  • 10

1 Answers1

4

Add the 'dynamic' keyword to the declaration of shouldFetchDataFromServer, and it should work.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60