Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect changes on NSUserDefaults

I'm developing an iOS application with latest SDK.

I want to know when a property on NSUserDefaults changes it value.

I have found this, but it is specific for macOS:

[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self     forKeyPath:[@"values." stringByAppendingString: @"MyPreference"]     options:NSKeyValueObservingOptionNew     context:NULL]; 

How can I do this on iOS?

like image 494
VansFannel Avatar asked Mar 04 '13 13:03

VansFannel


1 Answers

try out the NSUserDefaultsDidChangeNotification with this code snippet:

- (id)init {    self = [super init];    if(self) {      [[NSNotificationCenter defaultCenter] addObserver:self                                               selector:@selector(defaultsChanged:)                                                   name:NSUserDefaultsDidChangeNotification                                                 object:nil];   }   return self;     }  - (void)defaultsChanged:(NSNotification *)notification {   // Get the user defaults   NSUserDefaults *defaults = (NSUserDefaults *)[notification object];    NSLog(@"%@", [defaults objectForKey:@"yourIntrestedObject"]); }  - (void)dealloc {  [[NSNotificationCenter defaultCenter] removeObserver:self]; } 
like image 171
CarlJ Avatar answered Oct 21 '22 05:10

CarlJ