属性公开的私有变量 [英] Private variables which are exposed by properties

查看:60
本文介绍了属性公开的私有变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了一些文档,并尝试了Xcode和AppCode.但是我仍然不确定几件事.有人可以澄清一下吗?

I search some documentation, and tried Xcode and AppCode. But I'm still uncertain about few things. So can somebody clarify me:

  1. 如果我有一个名为foo的属性,是否应该有一个名为_foofoo的私有实例变量?

如果我创建私有实例变量,只需对其进行语法化.那我应该尝试访问self->fooself->_foo的什么变量?

If I dont't create a private instance variable, just syntetize it. Then what variable should I try to access self->foo or self->_foo ?

我已经看到了这两种方法,并且都可行,所以我很好奇是否有任何编码规则或约定,因为我没有找到任何方法.

I have seen both approaches and both worked so I'm curious if there is any coding rules or conventions for this because I didn't find any.

注意:我对@synthetize foo=_foo不感兴趣;

推荐答案

1..如果我有一个名为foo的属性,是否应该有一个名为_foo或foo的私有实例变量?

1. If I have property named foo, should I have private instance variable named _foo or foo?

您不必自己创建实例变量.将自动为您创建一个带有下划线前缀的实例变量.由于您不应该直接访问变量(请参见下文),因此您不必关心基础变量是什么.

You don't have to create the instance variable yourself. A instance variable, prefixed with an underscore will automatically be created for you. Since you shouldn't access the variable directly (see below) you shouldn't care about what the underlying variable is called.

2..如果我不创建私有实例变量,则将其语法化.那么我应该尝试使用什么变量来访问self-> foo或self-> _ foo?

2. If I dont't create a private instance variable, just syntetize it. Then what variable should I try to access self->foo or self->_foo ?

虚无.该属性的想法是使用访问器,而不是直接访问变量.您应该使用self.foo来获取和设置属性(如果您不喜欢点语法,则可以使用[self foo][self setFoo:newFoo];).另外请注意,您不必显式合成属性.

Niether. The idea of the property is to use the accessors instead of direct access to the variable. You should use self.foo to get and set the property (or [self foo] and [self setFoo:newFoo]; if you dislike the dot-syntax). Also note that you don't have to explicitly synthesize the property.

这篇关于属性公开的私有变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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