使用@property和@synthesise?

我想知道@property和@synthesise是什么意思。 目前我使用以下来声明一些东西:

//Class.m #import "Class.h" CCNode *node; @implementation //init, etc.. 

但是我看到其他人使用:

 @property (nonatomic, etc..) CCNode* node; @synthesise (nonatomic, etc..) node; //I am not too sure on how this type of declaration works, please correct me on how it's done. 

他们似乎都以同样的方式工作,@property和@synthesise方式的优点是什么? 他们做不同的事情,如果是的话,是什么?

@property@synthesize是两个客观的C关键字,允许你轻松创build你的属性,从而避免用手写入getter和setter方法的属性。

@property定义了属性本身,应该放在头文件中并且可以得到一些属性(例如:strong,nonatomic,retain assign,copy),@ @synthesize应该被放置到实现文件中并告诉编译器生成getter和setter方法的主体。

这两个关键字在正确使用属性的情况下非常有用 ,因为它们负责生成属性代码,并且最重要的是它们负责处理属性的内存pipe理。

@property – 创build你的getter和setter的声明。

@synthesize – 根据在属性中传递的参数提供getter和setter的定义。

看看这里,有更多关于同样的细节 – https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html

在使用@property ,编译器会根据readonly和readwrite声明getter和setter方法

 readonly -> getterMethod 

readwrite -> setter和getter方法使用@synthesize编译器将负责定义gettersetter方法

请阅读苹果关于Objective-C中属性的文档,以了解所有这些工作。

如果你的类中有一个实例variables(ivar),你通常不能从其他类访问它。 所以你必须build立公共访问方法(getter和setter)。 他们看起来像这样:

二传手:

 - (void)setMyVariable:(SomeClass *)newValue { if (newValue != myVariable) { [myVariable release]; myVariable = [newValue retain]; } } 

消气:

 - (SomeClass *)myVariable { return myVariable; } 

在Objective-C 2.0之前,这是你必须做的。 现在你可以使用@property和@synthesize来加快速度。 这基本上只是一个捷径。

在标题中使用@property来定义你想要的settertypes。 如果setter保留传递的值(如我的例子)或复制或只是分配?

在实现中,你只需编写@synthesize来使编译器在该位置包含自动创build的getter和setter。 通常在您的实施的顶部。

我的感觉是所有的iVars都应该有一个相关的下划线综合属性(使用_iVar可以防止意外的直接访问),除了init和dealloc方法之外,所有对iVar的访问都应该通过属性。

恕我直言,大赢家是内存pipe理 – 这是更安全,更容易,因为没有必要记住哪些iVar被保留。

考虑一下访问者需要做多less工作 – 4行代表获取者,2代表获取者。

在将来某个时候@synthesize可能是可选的,所以你只需要@property