简体   繁体   English

这2个@synthesize模式和推荐的有什么区别?

[英]What is the difference between this 2 @synthesize Pattern and which is Recommended?

many Places in the sample code i have seen 2 different way of @synthesize variable. 示例代码中的许多地方我已经看到了2种不同的@synthesize变量方式。 For Example here i am taking 1 sample button. 例如,我在这里采取1个样本按钮。 @property (strong, nonatomic) IBOutlet UIButton *logonButton; @property(强,非原子)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? 在这2种方法中哪一种推荐?

Short Answer 简答

The first method is preferred. 第一种方法是优选的。

Long Answer 答案很长

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 ). 第一个示例声明为logonButton属性生成的ivar应该是_logonButton而不是默认生成的ivar,它将与属性( logonButton )具有相同的名称。

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. 您可能会意外地将对象分配给您的ivar而不是您的属性,然后它将不会被保留,这可能会导致您的应用程序崩溃。

Example

@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]; 
}
  1. Means that the automatically generated set/get methods for the property are using an ivar with a different name - _logonButton. 意味着属性的自动生成的set / get方法使用具有不同名称的ivar - _logonButton。

    -(void)setLogonButton:(UIButton)btn {
    _logonButton = [btn retain]; // or whatever the current implementation is
    }

  2. Means that the automatically generated set/get methods for the property are using an ivar with the same name logonButton. 意味着属性的自动生成的set / get方法使用具有相同名称logonButton的ivar。

    -(void)setLogonButton:(UIButton)btn {
    logonButton = [btn retain]; // or whatever the current implementation is
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM