Skip to content

Instantly share code, notes, and snippets.

@alanjrogers
Created July 4, 2012 01:15
Show Gist options
  • Save alanjrogers/3044537 to your computer and use it in GitHub Desktop.
Save alanjrogers/3044537 to your computer and use it in GitHub Desktop.
KVO best practices
static NSString *MYObservationContext = @"MYObservationContext";
[object addObserver:self forKeyPath:@"key.path" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:(void*)&MYObservationContext];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if (context == &MYObservationContext) {
id oldValue = [change objectForKey:NSKeyValueChangeOldKey];
id newValue = [change objectForKey:NSKeyValueChangeNewKey];
// Do something
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
[object removeObserver:self forKeyPath:@"key.path" context:&MYObservationContext];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment