Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C variable... pointing to itself?

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.

like image 716
Justin Mrkva Avatar asked Apr 29 '13 02:04

Justin Mrkva


2 Answers

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];
like image 164
nschmidt Avatar answered Oct 09 '22 09:10

nschmidt


I think that the most accurate description would be "a self-referential pointer".

like image 38
Jonathan Avatar answered Oct 09 '22 09:10

Jonathan