Detect changes on NSUserDefaults
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];}
Use NSUserDefaultsDidChangeNotification for notification about change in User defaults:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsDidChange:) name:NSUserDefaultsDidChangeNotification object:nil];// notification- (void)defaultsDidChange:(NSNotification *)aNotification{ //}
Use KVO for notification about specific change in User defaults:
[[NSUserDefaults standardUserDefaults] addObserver:self forKeyPath:@"APXMyPropertyIamInterestedInKey" options:NSKeyValueObservingOptionNew context:NULL];// KVO handler-(void)observeValueForKeyPath:(NSString *)aKeyPath ofObject:(id)anObject change:(NSDictionary *)aChange context:(void *)aContext { // }
If you need to use this in a Swift 4 project you can use the following:
override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(defaultsChanged), name: UserDefaults.didChangeNotification, object: nil)}@objc func defaultsChanged() { // Your code}