Call function when if value in NSUserDefaults.stan

2019-05-31 03:38发布

问题:

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?

回答1:

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!



回答2:

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