简体   繁体   中英

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. For Example here i am taking 1 sample button. @property (strong, nonatomic) IBOutlet UIButton *logonButton;

1.@synthesize logonButton = _logonButton;

2.@synthesize logonButton;

among this 2 methods which one is recommended?

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 ).

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.

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.

    -(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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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