Skip to content

Instantly share code, notes, and snippets.

@mkhl
Created May 21, 2009 17:24
Show Gist options
  • Save mkhl/115578 to your computer and use it in GitHub Desktop.
Save mkhl/115578 to your computer and use it in GitHub Desktop.
Proper Key-Value Observer Usage
// Source: http://www.dribin.org/dave/blog/archives/2008/09/24/proper_kvo_usage/
// Define a static object; strings are easily readable, which is a plus
static NSString *const kOpeningBalanceChanged = @"openingBalance changed";
// Use it for the `context` parameter when adding KVO
[object addObserver:observer
forKeyPath:@"openingBalance"
options:options
context:kOpeningBalanceChanged];
// Compare to the static addresses to dispatch to the right observer
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if (context == &kOpeningBalanceChanged) {
// do something
}
[super observeValueForKeyPath:keyPath ...];
}
// When debugging, you can easily print the string
po *(id *)context
// You could even use a macro for defining these objects
#define DDDefineContext(_X_) static NSString *const _X_ = @#_X_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment