这 2 个 @synthesize 模式和推荐的模式有什么区别? [英] What is the difference between this 2 @synthesize Pattern and which is Recommended?

查看:60
本文介绍了这 2 个 @synthesize 模式和推荐的模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例代码中的很多地方我都看到了@synthesize 变量的两种不同方式.例如这里我拿了 1 个示例按钮.@property (strong, nonatomic) IBOutlet UIButton *logonButton;

many Places in the sample code i have seen 2 different way of @synthesize variable. For Example here i am taking 1 sample button. @property (strong, nonatomic) IBOutlet UIButton *logonButton;

1.@synthesize logonButton = _logonButton;

1.@synthesize logonButton = _logonButton;

2.@synthesize logonButton;

2.@synthesize logonButton;

这两种方法中,推荐哪一种?

among this 2 methods which one is recommended?

推荐答案

简短回答

首选第一种方法.

长答案

第一个示例声明为 logonButton 属性生成的 ivar 应该是 _logonButton 而不是默认生成的 ivar,后者将与属性具有相同的名称(<代码>登录按钮).

The first example is declaring that the generated ivar for the logonButton property should be _logonButton instead of the default generated ivar which would have the same name as the property (logonButton).

这样做的目的是帮助防止内存问题.您可能会不小心将一个对象分配给您的 ivar 而不是您的属性,然后它不会被保留,这可能会导致您的应用程序崩溃.

The purpose of this is to help prevent memory issues. It's possible that you would accidentally assign an object to your ivar instead of your property, and it would then not be retained which could potentially lead to your application crashing.

示例

@synthesize logonButton;

-(void)doSomething {
    // Because we use 'self.logonButton', the object is retained.
    self.logonButton = [UIButton buttonWithType:UIButtonTypeCustom];


    // Here, we don't use 'self.logonButton', and we are using a convenience
    // constructor 'buttonWithType:' instead of alloc/init, so it is not retained.
    // Attempting to use this variable in the future will almost invariably lead 
    // to a crash.
    logonButton = [UIButton buttonWithType:UIButtonTypeCustom]; 
}

这篇关于这 2 个 @synthesize 模式和推荐的模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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