I spotted this construct in some of Apple's example code for dealing with key-value observing. When adding an observer, you can add a context (in the form of a void* variable) that can uniquely identify the KVO call - particularly useful if you want multiple KVO calls to trigger the same action, as the single context can avoid using a bunch of chained or statements to check all the possibilities. This is the line that's used to declare the variable used for the context:
static void *aContext = &aContext;
It's basically declaring aContext to reference itself, assigning itself its own memory location - a brilliant trick that creates a unique identifier for the KVO context. Specifics aside, I'm curious what exactly this is called (self-assignment? circular pointer? something else?) and what other uses it may have besides KVO. I tried Googling different things but I couldn't come up with anything exactly like this, lacking the proper terminology. :)
I'm certainly going to be using this trick regularly, as it reduces the number of if statements necessary for KVO handling, which makes it that much more elegant.
I think this is overly complicated and confusing. When you want to have a unique context for KVO just declare it and use a pointer to it:
static int kMyObjectPropertyObservationContext;
...
[object addObserver:self
forKeyPath:@"myProperty"
options:0
context:&kMyObjectPropertyObservationContext];
I think that the most accurate description would be "a self-referential pointer".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With