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

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

问题描述

可能的重复:
在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 设置您的 ivar 以直接访问您的变量(当然绕过 KVC/KVO).

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 的 Cocoa 编码指南

From Apple's Coding Guidelines for Cocoa

...在许多情况下,当您使用声明的属性时,您还综合了一个对应的实例变量.

...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天全站免登陆