Ankit Vyas
Ankit Vyas

Reputation: 7501

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?

Upvotes: 3

Views: 150

Answers (2)

stan0
stan0

Reputation: 11817

  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
    }

Upvotes: 2

FreeAsInBeer
FreeAsInBeer

Reputation: 12979

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]; 
}

Upvotes: 7

Related Questions