Problems with NSUserDefaults and KVO

I am using NSUserDefaults in my application, and I would like to be notified when a particular value is changed. To do this, I added the following lines to viewDidLoad:

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults]; [settings synchronize]; [settings addObserver:self forKeyPath:@"pref_server" options:NSKeyValueObservingOptionNew context:NULL]; 

And the method for notification:

 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"Change"); NSUserDefaults *settings = [NSUserDefaults standardUserDefaults]; if (object == settings && [keyPath isEqualToString:@"pref_server"]) { NSLog(@"Server did change"); } } 

Unfortunately, the latter is never called ... @ "pref_server" is the identifier of the element that I set in Root.plist, in Settings.bundle. What am I doing wrong?

+7
ios
Apr 19 '11 at 9:18
source share
5 answers

I suggest using the appropriate notification: NSUserDefaultsDidChangeNotification .

Look for AppPrefs in the Apple Documentation in Xcode and this will show an example application that does exactly what you want to do. Just compile and run! It uses NSUserDefaultsDidChangeNotification .

This code is used to register an observer:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged:) name:NSUserDefaultsDidChangeNotification object:nil]; 
+16
Apr 19 '11 at 9:23 a.m.
source share

Interesting observation:

[NSUserDefaults standardUserDefaults] seems to be KVO compliant now, as I can observe and communicate with its values. I am using 10.7.2 using Xcode 4.2, SDK 10.7, LLVM compiler 3.0 .

I cannot find this new behavior documented anywhere in the release notes.

+6
Nov 23 '11 at 11:07
source share

NSUserDefaults does not meet KVO requirements, but NSUserDefaultsController. Therefore you should use:

 NSUserDefaultsController *defaultsc = [NSUserDefaultsController sharedUserDefaultsController]; [defaultsc addObserver:self forKeyPath:@"values.pref_server" options:NSKeyValueObservingOptionNew context:NULL]; 
+2
Sep 18 '11 at 0:00 a.m.
source share

Although not well documented, NSUserDefaults support monitoring key values ​​in iOS7.

+2
Sep 29 '13 at 4:56 on
source share

Starting with iOS 11.3, this works and is documented:

Respond to default changes

You can use key value monitoring to be notified of any updates to a specific default value.

0
Mar 28 '18 at 16:26
source share



All Articles