iOS头文件中的属性和变量之间的区别? [英] Difference between properties and variables in iOS header file?

查看:103
本文介绍了iOS头文件中的属性和变量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Objective-c中的实例变量和属性之间是否有区别?

self.ivar和ivar之间的区别?

在@interface行后面的括号中声明变量和定义下面的属性之间有什么区别?

What is the difference between declaring variables in brackets immediately after the @interface line, and defining properties below?

例如......

@interface GCTurnBasedMatchHelper : NSObject {
BOOL gameCenterAvailable;
BOOL userAuthenticated;
}

@property (assign, readonly) BOOL gameCenterAvailable;


推荐答案

在括号中定义变量只是声明它们的实例变量。

Defining the variables in the brackets simply declares them instance variables.

根据括号内的标准,声明(和合成)属性会为实例变量生成getter和setter。这在Objective-C中尤其重要,因为通常通过getter和setter来管理内存(例如,当一个值被分配给ivar时,通过setter来保留并最终释放所分配的对象)。除了内存管理策略之外,该实践还促进了封装并减少了原本需要的普通代码量。

Declaring (and synthesizing) a property generates getters and setters for the instance variable, according to the criteria within the parenthesis. This is particularly important in Objective-C because it is often by way of getters and setters that memory is managed (e.g., when a value is assigned to an ivar, it is by way of the setter that the object assigned is retained and ultimately released). Beyond a memory management strategy, the practice also promotes encapsulation and reduces the amount of trivial code that would otherwise be required.

在括号中声明ivar是很常见的然后是一个相关的属性(如在你的例子中),但这不是绝对必要的。定义属性和合成就是所需要的,因为隐式地合成属性也会创建一个ivar。

It is very common to declare an ivar in brackets and then an associated property (as in your example), but that isn't strictly necessary. Defining the property and synthesizing is all that's required, because synthesizing the property implicitly also creates an ivar.

Apple目前建议的方法(在模板中)是:

The approach currently suggested by Apple (in templates) is:

在头文件中定义属性,例如:

Define property in header file, e.g.:

@property (assign, readonly) gameCenter;

然后综合&在实现中声明ivar:

Then synthesize & declare ivar in implementation:

@synthesize gameCenter = __gameCenter;

最后一行合成 gameCenter 属性和断言,分配给该属性的任何值都将存储在 __ gameCenter ivar中。同样,这不是必需的,但通过定义合成器旁边的ivar,您将减少必须键入ivar名称的位置,同时仍明确命名它。

The last line synthesizes the gameCenter property and asserts that whatever value is assigned to the property will be stored in the __gameCenter ivar. Again, this isn't necessary, but by defining the ivar next to the synthesizer, you are reducing the locations where you have to type the name of the ivar while still explicitly naming it.

这篇关于iOS头文件中的属性和变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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