Objective-C的变量...指着自己? [英] Objective-C variable... pointing to itself?

查看:108
本文介绍了Objective-C的变量...指着自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这个结构在​​一些苹果公司的例子code的处理键 - 值观察。当添加一个观察者,你可以添加上下文(以一个void *变量的形式),可以唯一地标识志愿通话 - 如果你想特别有用多个志愿调用触发同样的动作,作为单一的情况下,可避免使用一堆链或报表做好一切准备。这是公司用来声明用于环境变量的行:

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;

这基本上宣布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.

推荐答案

我认为这是过于复杂和混乱。当你想为KVO一个独特的环境只需要声明并使用一个指向它:

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

这篇关于Objective-C的变量...指着自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆