Reputation: 107
I'm wondering if there's a way to track changes of state of a key in the user dictionary defaults.
I don't need to check if it's true or false, I just need to know if it changed.
Here's my scenario: I have an iAP product that unlocks some feature, and I want these features to be available as soon as they are purchased, without rebooting the app or loging out.
So I implemented the willAppear method on the view that has the features, to check through a key if purchase was made.
The problem with this is that if the key is true (purchased done) it will perform several tasks, but I don't need to perform this tasks EVERY time a user purchased the iAP product use the app.
Thank you.
Upvotes: 0
Views: 191
Reputation: 9913
You can use KVO (Key Value Observer) for this.
If you want to detect changes with specic key the use :
[[NSUserDefaults standardUserDefaults] addObserver:self
forKeyPath:@"YOUR_KEY_HERE"
options:NSKeyValueObservingOptionNew
context:NULL];
and if want to detect changes whenever NSuserdefauls any key is changed..
Using NSUserDefaultsDidChangeNotification
you can detect when any change will be done in the key value.
So firstly add Observer : [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged:) name:NSUserDefaultsDidChangeNotification object:nil];
and then detect using :
- (void)defaultsChanged:(NSNotification *)notification {
// Get the user defaults
NSUserDefaults *defaults = (NSUserDefaults *)[notification object];
NSLog(@"%@", [defaults objectForKey:@"YOUR_KEY"]);
}
Hope it helps you.
Upvotes: 3