美文网首页
iOS @property @synthesize MRC下的要

iOS @property @synthesize MRC下的要

作者: VinZZZZ | 来源:发表于2019-10-10 10:51 被阅读0次

1. 只使用@property

在MRC下,如下代码

@interface ViewController ()
@property(nonatomic, retain) NSDate* d1111;
@end

使用xcrun -sdk iphonesimulator clang -rewrite-objc ViewController.m ,可以看到对应生成了名为_d1111的变量:

image.png
因此可以直接对_d1111取值和赋值。
同时,也可以看到生成了get, set方法:
image.png ,其操作的值都是_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:

image.png
同时,get, set方法也是对d1111进行的操作:
image.png 方法名里用到自然也是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)进行访问,在其他地方则要尽量使用。

相关文章

网友评论

      本文标题:iOS @property @synthesize MRC下的要

      本文链接:https://www.haomeiwen.com/subject/fwropctx.html