How to use KVO for UserDefaults in Swift?

前端 未结 4 1550
耶瑟儿~
耶瑟儿~ 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-04 01:31

    For anyone who will be looking for the answer in the future, didChangeNotification will be posted only if changes are made on the same process, if you would like to receive all updates regardless of the process use KVO.

    Apple doc

    This notification isn't posted when changes are made outside the current process, or when ubiquitous defaults change. You can use key-value observing to register observers for specific keys of interest in order to be notified of all updates, regardless of whether changes are made within or outside the current process.

    Here is a link to demo Xcode project which shows how to setup block based KVO on UserDefaults.

提交回复
热议问题