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.)
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.
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.
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.
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];
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With