Cocoa - Notification on NSUserDefaults value change?

SirRatty picture SirRatty · Jul 17, 2009 · Viewed 21.3k times · Source

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.)

Answer

SirRatty picture SirRatty · Jul 17, 2009

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];