views:

650

answers:

3

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

+8  A: 

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." stringByAppendingString: @"MyPreference"]
    options:NSKeyValueObservingOptionNew
    context:NULL];
SirRatty
A: 

Why are you appending a string literal to a string literal instead of just writing the whole thing as one?

Preston
This should have been a comment and not an answer.
Niels Hansen
Niels Hansen: He only has 9 karma (19 before the downvote). You need 50 karma to post comments.
Peter Hosey
Preston Sumner: Most likely to make it easy for the user of that code to replace the literal `@"MyPreference"` with a variable.
Peter Hosey
Niels Hansen: As a new user, I didn't have the karma to post a comment. The always helpful and independent-minded Stack Overflow users went ahead and voted me down to make it even harder to get to that point.
Preston
This "answer" (comment) adds nothing to discussion at hand.
DenNukem
It's also almost a year old, when I was new to the site and also didn't have the karma to post comments.
Preston
+1  A: 

And Apple employee advised to use NSUserDefaultsDidChangeNotification notification over here: https://devforums.apple.com/message/237718#237718

DenNukem