Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa - Notification on NSUserDefaults value change?

Let's say I have a key @"MyPreference", with a corresponding value stored through NSUserDefaults.

Is there a way to be notified when the value is modified?

Or could it be done through bindings? (But this case, instead of binding the value to a UI element, I wish my object to be notified of the change, so that I can perform other tasks.)

I am aware that NSUserDefaultsDidChangeNotification can be observed, but this appears to be a all-or-nothing approach, and there does not appear to be a mechanism there to get at the specific key-value-pair that was modified. (Feel free to correct.)

like image 609
SirRatty Avatar asked Jul 17 '09 03:07

SirRatty


People also ask

How do you check if NSUserDefaults is empty in Objective C?

There isn't a way to check whether an object within NSUserDefaults is empty or not. However, you can check whether a value for particular key is nil or not.

What is NSUserDefaults?

The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.

How do you save NSUserDefaults in Objective C?

static func setObject(value:AnyObject ,key:String) { let pref = NSUserDefaults. standardUserDefaults() pref. setObject(value, forKey: key) pref. synchronize() } static func getObject(key:String) -> AnyObject { let pref = NSUserDefaults.


2 Answers

Spent all day looking for the answer, only to find it 10 minutes after asking the question...

Came across a solution through Key-Value-Observing:

[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self     forKeyPath:@"values.MyPreference"     options:NSKeyValueObservingOptionNew     context:NULL]; 

Or, more simply (per comment below):

[[NSUserDefaults standardUserDefaults] addObserver:self                                         forKeyPath:@"MyPreference"                                            options:NSKeyValueObservingOptionNew                                            context:NULL]; 
like image 171
SirRatty Avatar answered Oct 02 '22 05:10

SirRatty


Swift:

override func viewDidLoad() {   super.viewDidLoad()   NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: "THE KEY", options: NSKeyValueObservingOptions.New, context: nil) }  override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {   // your logic }  deinit {   NSUserDefaults.standardUserDefaults().removeObserver(self, forKeyPath: "THE KEY") } 
like image 45
Brian Avatar answered Oct 02 '22 05:10

Brian