NSUserDefaults KVO in iOS7

Though its not well documented, NSUserDefaults do support key-value observing in iOS7. The following code works:

- (void)viewDidLoad{
  [super viewDidLoad];
  NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
  [ud addObserver:self forKeyPath:@"bar" options:NSKeyValueObservingOptionOld|NSKeyValueObservingOptionNew context:nil];
  [ud setObject:@"foo" forKey:@"bar"];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
  NSLog(@"%@", change);
}

Its much more convenient then using NSUserDefaultsDidChangeNotification, since we do know exactly which key is changing.

As the hardware of mobile devices become more and more powerful, I hope the support of key binding could be actualised in near future🙂

NSUserDefaults KVO in iOS7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s