Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive NSUserDefaultsDidChangeNotification iphone

Tags:

After a lot of searching I was not able to find whether you need to pass a dictionary object to:

[NSUserDefaultsDidChangeNotification addObserver: forKeyPath: options: context:]; 

and what should be provided in options if I want to be notified for even a single change in the userDefaults. Also what is keypath?

like image 391
neha Avatar asked Jul 02 '10 14:07

neha


People also ask

How does NSUserDefaults work?

NSUserDefaults caches the information to avoid having to open the user's defaults database each time you need a default value. When you set a default value, it's changed synchronously within your process, and asynchronously to persistent storage and other processes.

What is NSUserDefaults in Swift?

A property list, or NSUserDefaults can store any type of object that can be converted to an NSData object. It would require any custom class to implement that capability, but if it does, that can be stored as an NSData. These are the only types that can be stored directly.


1 Answers

NSUserDefaultsDidChangeNotification is just a notification that is sent out when the defaults are changed. To listen out for it you need this code :

    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];     [center addObserver:self                selector:@selector(defaultsChanged:)                      name:NSUserDefaultsDidChangeNotification                  object:nil]; 

This will call the method defaultsChanged: when the notification is fired. You need to implement this method like this :

- (void)defaultsChanged:(NSNotification *)notification {     // Get the user defaults     NSUserDefaults *defaults = (NSUserDefaults *)[notification object];      // Do something with it     NSLog(@"%@", [defaults objectForKey:@"nameOfThingIAmInterestedIn"]); } 
like image 184
deanWombourne Avatar answered Sep 26 '22 05:09

deanWombourne