I have a variable that become value from NSUserDefaults.standardUserDefaults()
var GiftCount = NSUserDefaults.standardUserDefaults().valueForKey("Gift") as! Int
And i have a function named setGiftCount()...
I need call this function when variable GiftCount has changed... How to do it?
First
NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: "Gift", options: NSKeyValueObservingOptions.New, context: nil)
Second
deinit {
NSUserDefaults.standardUserDefaults().removeObserver(self, forKeyPath: "Gift")
}
Third
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
setGiftCount()
}
P.S. Thank you for down votes!
You can add an observer for NSUserDefaultsDidChangeNotification to your view controller:
adding:
NotificationCenter.default.addObserver(self, selector: #selector(userDefaultsDidChange), name: UserDefaults.didChangeNotification, object: nil)
removing it:
NotificationCenter.default.removeObserver(self, name: UserDefaults.didChangeNotification, object: nil)
and add the selector method:
func userDefaultsDidChange(_ notification: Notification) {
// your code... setGiftCount()
}