将属性观察者添加到Swift中的全局变量中



i在全局范围上声明的变量globalVariable可能随时更改。

globalVariable改变时,我的应用程序中不同的ViewControllers需要做出不同的反应。

因此,希望在globalVariable更改时执行所需代码的每个ViewController中添加属性观察者。

我似乎无法使用overrideextension 实现它。去这里有什么方法?

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

extension NSNotification.Name {
    static let globalVariableChanged = NSNotification.Name(Bundle.main.bundleIdentifier! + ".globalVariable")
}
var globalVariable: Int = 0 {
    didSet {
        NotificationCenter.default.post(name: .globalVariableChanged, object: nil)
    }
}

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

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

注意,如果(a)全局变量是参考类型,即 class,则此didSet机制将无法检测更改。(b)它仅突变为全局变量引用而不是用新实例替换的对象。要确定这种情况,您需要使用KVO或其他机制来检测突变。

可以为您的全局变量有一个Didset {}函数,并且必须属于变量本身。您可以做的是使变量的didset {}函数调用来自其他对象的函数列表。

您可以为此使用通知,也可以构建自己的机制。

这是如何创建自己的机制的一个示例:

(请注意,这是非常通用的,可以适用于任何变量类型或Singleton实例)

// Container for an observer's function reference
// - will be used to call the observer's code when the variable is set
// - Separates the object reference from the function reference
//   to avoid strong retention cycles.
struct GlobalDidSet<T>
{
   weak var observer:AnyObject?
   var didSetFunction:(AnyObject)->(T)->()
   init(_ observer:AnyObject, didSet function:@escaping (AnyObject)->(T)->())
   {
      self.observer  = observer
      didSetFunction = function
   }
}
// Container for a list of observers to be notified
// - maintains the list of observers
// - automatically clears entries that non longer have a valid object
// - calls all observers when variable changes
// - erases type of observer to allow generic use of GlobalDidSet<>
struct GlobalDidSets<T>
{
   var observers : [GlobalDidSet<T>] = []
   mutating func register<O:AnyObject>(_ observer:O, didSet function:@escaping (O)->(T)->())
   {
      let observer = GlobalDidSet<T>(observer)
      { (object:AnyObject) in function(object as! O) }
      observers.append(observer)  
   }
   mutating func notifyDidSet(_ oldValue:T)
   {
      observers = observers.filter{$0.observer != nil}
      observers.forEach{ $0.didSetFunction($0.observer!)(oldValue) }
   }
}

...

// To use this, you will need a second variable to manage the list of observers
// and your global variable's didSet{} must use that observer list
// to perform the multiple function calls
//
var globalVariableDidSets = GlobalDidSets<String>()
var globalVariable : String = "Initial Value"
{
   didSet { globalVariableDidSets.notifyDidSet(oldValue) }
}
// In your view controllers (or any other class), you need to setup the 
// reaction to the global variable changes by registering to the observer list
//
class MyVC:UIViewController
{
    override func viewDidLoad()
    {
      globalVariableDidSets.register(self){ $0.handleVariableChange }  
      // ...
    }
    func handleVariableChange(_ oldValue:String)
    {
      //...
    }
}

最新更新