Cocoa - Notification on NSUserDefaults value change?
CocoaNotificationsPreferencesCocoa Problem Overview
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.)
Cocoa Solutions
Solution 1 - Cocoa
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];
Solution 2 - Cocoa
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")
}
Solution 3 - Cocoa
And Apple employee advised to use NSUserDefaultsDidChangeNotification notification over here: https://devforums.apple.com/message/237718#237718
Solution 4 - Cocoa
I agree with @DenNukem. I was using the NSKeyValueObservingOptionNew
. But this function started giving me the BAD_ACCESS Code=1
error wherever I used the NSUserDefault
in order to save other objects. In case you are using Key-Value Observer (KVC), just be aware of the Zombie issue on NSUserDefaults
.
Here is the link to the solution: https://stackoverflow.com/questions/5714161/nsuserdefaults-and-kvo-issues