Cocoa - Notification on NSUserDefaults value change?
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")
}
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];