Objective-C variable… pointing to itself?

喜夏-厌秋 提交于 2019-12-03 08:58:55

问题


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.


回答1:


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];



回答2:


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



来源:https://stackoverflow.com/questions/16270323/objective-c-variable-pointing-to-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!