1. 只使用@property
在MRC下,如下代码
@interface ViewController ()
@property(nonatomic, retain) NSDate* d1111;
@end
使用xcrun -sdk iphonesimulator clang -rewrite-objc ViewController.m
,可以看到对应生成了名为_d1111
的变量:

因此可以直接对
_d1111
取值和赋值。同时,也可以看到生成了get, set方法:

_d1111
,但是方法名里用到都是d1111
:_I_ViewController_d1111
, _I_ViewController_setD1111_
。因此使用self.d1111
访问的就是这两个方法。
2. 添加@sythesize
@interface ViewController ()
@property(nonatomic, retain) NSDate* d1111;
@end
@implementation ViewController
@synthesize d1111;
- (void)dealloc
{
[self.d1111 release];
[super dealloc];
}
@end
之后,可以看到对应的变量名变为d1111
:

同时,get, set方法也是对
d1111
进行的操作:
d1111
:_I_ViewController_d1111
, _I_ViewController_setD1111_
。因此,加不加@synthesize, 对于self.d1111
访问的方法其实都是一样的。而如果不加self.
,则仍然是直接访问变量,而不是通过get/set方法进行访问。
总结:加了@sythesize,只是对原来默认的变量进行改名,由带下划线的变量名改为指定的名字,其他没有任何影响。
3. 最佳实践
参考 Advanced Memory Management Programming Guide 中的说明, 在init和dealloc中不要使用self.xxx(accessor)进行访问,在其他地方则要尽量使用。
网友评论