iOS NSUserDefaults Watching the change of values for a single key

后端 未结 4 477
花落未央
花落未央 2020-12-15 21:52

I have the following code aiming to catch the event of a NSUserDefaults value changing for a particular key.

 [[NSUserDefaults standardUserDefaults] addObse         


        
4条回答
  •  一整个雨季
    2020-12-15 22:17

    Swift 5 Version:

    extension UserDefaults {
        @objc dynamic var keyPath: Int {
            return integer(forKey: "keyPath")
        }
    }
    

    HINT: make sure the var has exactly the same as the keyPath

    and where you use the observer do:

    var observer: NSKeyValueObservation?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        observer = UserDefaults.standard.observe(\.keyPath, options: [.initial, .new], changeHandler: { (defaults, change) in
            //Do something
        })
    }
    
    deinit {
        observer?.invalidate()
    }
    

提交回复
热议问题