How to use KVO for UserDefaults in Swift?

前端 未结 4 1547
耶瑟儿~
耶瑟儿~ 2021-02-04 01:00

I\'m rewriting parts of an app, and found this code:

fileprivate let defaults = UserDefaults.standard

func storeValue(_ value: AnyObject, forKey key:String) {
          


        
4条回答
  •  野性不改
    2021-02-04 01:50

    From the blog of David Smith http://dscoder.com/defaults.html https://twitter.com/catfish_man/status/674727133017587712

    If one process sets a shared default, then notifies another process to read it, then you may be in one of the very few remaining situations that it's useful to call the -synchronize method in: -synchronize acts as a "barrier", in that it provides a guarantee that once it has returned, any other process that reads that default will see the new value rather than the old value.

    For applications running on iOS 9.3 and later / macOS Sierra and later, -synchronize is not needed (or recommended) even in this situation, since Key-Value Observation of defaults works between processes now, so the reading process can just watch directly for the value to change. As a result of that, applications running on those operating systems should generally never call synchronize.

    So in most likely case you do not need to set to call synchronize. It is automatically handled by KVO.

    To do this you need add observer in your classes where you are handling persistanceServiceValueChangedNotification notification. Let say you are setting a key with name "myKey"

    Add observer in your class may be viewDidLoad etc

     UserDefaults.standard.addObserver(self, forKeyPath: "myKey", options: NSKeyValueObservingOptions.new, context: nil)
    

    Handle the observer

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    
        //do your changes with for key
    }
    

    Also remove your observer in deinit

提交回复
热议问题