目标C-综合属性 [英] Objective C - Synthesize property

查看:72
本文介绍了目标C-综合属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
在目标C中用下划线前缀属性名称

Possible Duplicate:
Prefixing property names with an underscore in Objective C

综合属性时,我发现有人在做

When synthesizing properties I found out that someone is doing:

@synthesize myVar = _myVar;

什么是"_myVar",这与简单地执行操作有何区别:

what is "_myVar" and which is the difference with simply doing :

@synthesize myVar;        

最后什么时候我应该比第一个更喜欢第一个解决方案?

Lastly when I should prefer the first solution to the last one?

谢谢 卢卡

推荐答案

在您的示例中,真正的_myVar是支持您的属性的ivar的名称.默认情况下,当您合成属性时,将为您创建一个同名的ivar.因此,您可以使用属性通过setter/getter或_myVar来直接访问变量(当然,绕过KVC/KVO)来设置ivar.

What _myVar really is in your example, is the name of the ivar that is backing your property. By default, when you synthesize a property, an ivar of the same name is created for you. So, you can use your property to set your ivar through setter/getter or the _myVar to directly access your variable (bypassing KVC/KVO of course).

从Apple的可可编码准则

...在许多情况下,当您使用声明的属性时,也会合成 相应的实例变量.

...In many cases, when you use a declared property you also synthesize a corresponding instance variable.

确保实例变量的名称简洁地描述了 属性已存储.通常,您不应该访问实例变量 直接,而是应该使用访问器方法(您可以访问 实例变量直接在init和dealloc方法中).为了帮助 发出信号,在实例变量名前加上下划线(_)...

Make sure the name of the instance variable concisely describes the attribute stored. Usually, you should not access instance variables directly, instead you should use accessor methods (you do access instance variables directly in init and dealloc methods). To help to signal this, prefix instance variable names with an underscore (_)...

这篇关于目标C-综合属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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