何时使用“自我"访问属性 [英] When to access properties with 'self'

查看:71
本文介绍了何时使用“自我"访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在该网站上阅读了有关此问题的许多问题,我了解以下内容:

I have read a number of questions on this site about this issue, I understand the following:

self.property访问手动创建或通过@synthesize创建的getter/setter方法.取决于是否将该属性声明为保留,复制等.保留计数是否被正确修改(例如,保留属性),释放使用"retain"分配了新值的先前值,并将保留计数增加1.

self.property accesses the getter/setter method created manually or by @synthesize. Depending upon whether the property is declared as retain, copy etc. the retain count is modified correctly, for example a retained property, releases the previous value assigned the new value with 'retain' and increments the retain count by 1.

属性通常用相同名称的实例变量声明(如果您手动进行赋值,则可以不同).这通常是因为@synthesize生成的访问器使用实例变量来引用内存中的对象,然后执行相关命令.

Properties are usually declared with instance variables of the same name (can be different if you make the assignment manually). This is generally because the @synthesize generated accessors use the instance variable to reference the object in memory and then perform the relevant commands.

我的问题基于这样一个事实:在许多示例中,self.property和property可互换地用于不同的事物,而我在确定规则时遇到了麻烦. Apple Docs的食谱"示例应用程序中的一个示例具有以下内容:

My question is based on the fact that in many examples, self.property and property are used interchangeably for different things and I'm having troubles determining the rules. One example in the 'Recipes' example app in the Apple Docs, has the following:

self.navigationItem.title = recipe.name;
nameTextField.text = recipe.name;    
overviewTextField.text = recipe.overview;    
prepTimeTextField.text = recipe.prepTime; 

和...

self.ingredients = sortedIngredients;

每个属性都有关联的同名私有实例变量.所有属性都以非原子,保留"属性以相同的方式声明.每个都在dealloc中释放...

Each of these properties have associated private instance variables of the same name. All are declared in the same way with 'nonatomic, retain' attributes. Each are released in dealloc...

但是,成分"是通过self访问的,而"prepTimeTextField"是直接访问的.

Yet 'ingredients' is accessed through self and 'prepTimeTextField' is accessed directly.

访问方式不同的原因是什么?

What is the reason for the difference in access methods?

如果我正在访问视图的委托,该怎么办?还是之前的视图控制器将其作为保留属性传递给视图控制器的核心数据对象?

What about if I'm accessing a view's delegate? Or a core-data object which was passed to a view controller by it's previous view controller as a retained property?

非常感谢

推荐答案

您几乎总是想使用合成的setter/getter来访问变量,即使您此时并没有做任何特别的事情.

you almost always want to access variables using the synthesized setters/getters, even if you aren't doing anything special with them at the moment.

如果随着应用程序的开发,您发现您需要进行变量的进一步验证/格式化,那么您就可以实现所需的setter/getter方法,并且如果您使用了综合方法,则将调用此代码.

if as your application develops, you find that you need to be doing further validation/formatting of variables, then you can just implement the required setter/getter method, and if you have used the synthesised methods this code will get called.

这通常是个好习惯.

这篇关于何时使用“自我"访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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