iOS Observer NSUserDefaults Boolean value change

1) imagine we have a NSUserDefaults boolean value set status

[[NSUserDefaults standardUserDefaults]setBool: YES forKey:@"status"];

2) Now add an observer for this in the object where u want to handle the change 

[[NSUserDefaults standardUserDefaults] addObserver: self forKeyPath:@"status"  options:NSKeyValueObservingOptionNew context:nil];

3) Add protocol method (NSObject by default has an implementation of this) 
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
{
 if([keyPath isEqualToString:@"status"]) {
//  Add the code
}

}



No comments: