Created
March 14, 2013 03:35
-
-
Save ddribin/5158614 to your computer and use it in GitHub Desktop.
Evil KVO context hack using macros + C99 compound literal syntax.
This file contains 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
// Building upon: http://www.dribin.org/dave/blog/archives/2008/09/24/proper_kvo_usage/ | |
// Defines a unique KVO context by taking the address of a 2-element string array. | |
// Using __FILE__ ensures the address is unique across source files, even with link time optimization. | |
#define DDDefineContext(_X_) static void * _X_ = &(const char *[] ) {#_X_, __FILE__} | |
// Example Definition | |
DDDefineContext(MyFooContext); | |
// Example Usage. No need for &MyFooContext to make it unique. | |
- (void)startObserving | |
{ | |
[_ivar addObserver:self forKeyPath:@"foo" options:0 context:MyFooContext]; | |
} | |
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context | |
{ | |
// In a debugger, use `p *(char **)context` to dump the context | |
if (context == MyFooContext) { | |
// foo changed | |
} else { | |
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context]; | |
} | |
} | |
- (void)stopObserving | |
{ | |
[_ivar removeObserver:self forKeyPath:@"foo" context:MyFooContext]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Because gist comment markdown sucks, I didn't realize you folks were referring to the shell-like backtick syntax. I was worried vararg macros were somehow involved…