将属性观察器添加到 Swift 中的类内的全局变量

Mar*_*dor 3 properties global-variables ios swift

globalVariable在全局范围内声明了一个可能随时更改的变量。

不同的ViewControllers在我的应用程序需要做出不同的反应,当globalVariable变化。

因此,最好在每个属性中添加一个属性观察器,ViewController以便在globalVariable更改时执行所需的代码。

我似乎无法使用overrideor实现它extension去这里的路是什么?

Rob*_*Rob 7

如果您的目标是简单地知道您的全局变量何时更改,您可以让它在更改时发布通知:

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

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

然后任何对象都可以为该通知添加一个观察者:

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

}
Run Code Online (Sandbox Code Playgroud)

请注意,didSet如果 (a) 全局变量是引用类型,即 a class;(b) 它只是改变全局变量引用的对象,而不是用新实例替换它。要识别该场景,您需要使用 KVO 或其他机制来检测突变。