Objective-C variable… pointing to itself?

2019-03-12 13:37发布

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.

2条回答
Evening l夕情丶
2楼-- · 2019-03-12 13:49

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

查看更多
疯言疯语
3楼-- · 2019-03-12 13:57

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];
查看更多
登录 后发表回答