Dmitry
Dmitry

Reputation: 3079

Call function when if value in NSUserDefaults.standardUserDefaults() changes

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?

Upvotes: 3

Views: 7815

Answers (2)

Dmitry
Dmitry

Reputation: 3079

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

Upvotes: 24

Leo Dabus
Leo Dabus

Reputation: 236360

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

Upvotes: 14

Related Questions