16

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.

Mike Mertsock
  • 11,825
  • 7
  • 42
  • 75
jstm88
  • 3,335
  • 4
  • 38
  • 55
  • I like this trick too (and thanks for pointing it out) but truth be told, it is not much simpler than `static char *aContext = "anything" ;`, which works the same way. – Monolo Apr 29 '13 at 17:03
  • http://stackoverflow.com/questions/2532102/can-a-pointer-ever-point-to-itself – Greg Apr 30 '13 at 03:01
  • 2
    According to http://stackoverflow.com/a/2532108/834998, this may also be useful in circular lists of length 1. Personally, I wouldn't call this an amazing trick; it's just an easy way to get a unique identifier that's valid *for the current execution of the app*, provided you create all other unique identifiers the same way. – Greg Apr 30 '13 at 03:04
  • 1
    It's self referential as @Jonathan said.A bit more discussion could be found at [cocoa dev list](http://www.cocoabuilder.com/archive/cocoa/322754-static-void-declaration-in-apple-example-code.html) – Bob Cromwell May 08 '13 at 09:22

2 Answers2

2

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];
nschmidt
  • 2,383
  • 16
  • 22
1

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

Jonathan
  • 25,873
  • 13
  • 66
  • 85