[cocos2d]經常見人用@synthesize xxx = _xxx;這種方式有甚麼好處和用途

經常見人用@synthesize xxx = _xxx;這種方式有甚麼好處和用途

在interface中

ccsprite * _xxx
@property (nonatomic, retain) ccsprite *xxx;

在implementation中
@synthesize xxx = _xxx

這個方法有甚麼好處和用途?

同问!。。。。。。。。。。。。。,,,,

@property (nonatomic, retain) NSString *attribute;

@synthesize attribute = _attribute;

这样给你两种方式赋值:

_attribute = ***;//直接赋值 可以作为变量简单的使用

self.attribute = ***;//这个时候会调用attribute的set方法来复制,实际上是这样的

;

而属性里设置的是retain所以set方法是这样的:

- (void)setAttribute:(NSString *)temp

{

;

attribute release];

attribute = temp;

}

相应的取值也会调用get方法。

把retain换成strong就不用@synthesize 可以直接使用_var

那就是說
已經不用再用
@synthesize xxx = _xxx
這個方法?

@synthesize attribute = attribute;
这种写法也可以写成 @synthesize attribute = attribute
;
当变量的时候用就是attribute_ = ***;
苹果只是在xcode某个版本升级后,你只需要写@synthesize attribute;
就默认是你写了@synthesize attribute = _attribute;
方便程序员罢了,不过我用4.6.3发现又不能了,但这个不要紧,只是个形式问题。

而strong和weak是ARC用的

xcode 4.2还是几以上就不需要@synthesize attribute = _attribute; 了

直接@property (nonatomic, retain) NSString *attribute;之后

就可以直接使用_attribute = ;

還是不太懂=_=
能說簡單一點嗎?謝謝

就是说xcode 4.2以上,系统已经自动帮你补全了这一句,不用管了。
至于具体作用,就是简化了setter和getter的使用,看一下property的具体用法就可以了

一般是这样的如果不这样写。然后自己写这个属性的set方法时,

比如属性叫proper好了。

- (void)setProper:(NSString *)aProper

{

// _proper是proper的别名,在类的内部使用。proper提供给调用者。

// 下面这句赋值就相当于给proper赋值了。如果没有这个_proper别名。

// 而是直接赋值的话,proper = aProper; 那么就引起setProper的递归调用了。

// setProper是给proper设置值的函数,每一次给proper赋值都会调用该函数。

// 那么就形成了无限循环了。所以我们用一个别名来给他赋值。

// 一般要显示写出这个setProper函数是为了,在赋值完成之后去刷新某些数据或界面之类的。

_proper = aProper;

// 调用刷新数据或界面函数。

}

确切的说,_xxx是成员变量 xxx用@property定义的是属性 属性必须用self + .的方式访问 如self.xxx 用@synthesize后你不用自己写set/get了 而@synthesize xxx = _xxx;是让属性与成员变量相等 这样_xxx也能访问self.xxx了 成员变量是不能通过self._xxx访问的 xxx属性必须通过self.xxx 让他们相等后 self.xxx等效_xxx