Created
May 21, 2009 17:24
-
-
Save mkhl/115578 to your computer and use it in GitHub Desktop.
Proper Key-Value Observer Usage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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