Reputation: 19879
I saw a sample code with this code:
in the .h file:
CALayer *_animationLayer;
@property (nonatomic, retain) CALayer *animationLayer;
And in the .m file:
@synthesize animationLayer = _animationLayer;
I am guessing it is related to the retain count?
Can someone explain that?
Upvotes: 0
Views: 170
Reputation: 54854
The code in the .h file is declaring two things, a variable called _animationLayer
which is of type CALayer*
, and a property called animationLayer
which is also of type CALayer*
. The code in the .m file is instructing the objective-c compiler to automatically generate getters and setters for the animationLayer
property, using the _animationLayer
variable to hold the actual value that is set.
So for instance:
_animationLayer = nil; //initialize the variable to nil
self.animationLayer = [[CALayer alloc] init]; //assign a value to the property
NSLog("_animationLayer is: %@", _animationLayer); //it's not set to nil anymore
_animationLayer = nil; //set it to nil again
NSLog("self.animationLayer is: %@", self.animationLayer); //now the property is nil
And you're correct, this does have some relationship to the object's retainCount (so it's not quite correct to think of the variable as a direct alias for the property). In essence, setting the value directly using the _animationLayer
variable does not retain the new value or release the old value. Setting the value using the property accessor does. For example:
_animationLayer = [[CALayer alloc] init]; //retain count is 1
self.animationLayer = nil; //retain count is 0
self.animationLayer = [[CALayer alloc] init]; //oops, retain count is 2
self.animationLayer = nil; //retain count is 1, the object leaked
_animationLayer = [[CALayer alloc] init]; //retain count is 1
[_animationLayer release]; //retain count is 0
self.animationLayer = nil; //oops, just released it again
Upvotes: 1
Reputation: 27601
Consider it like an alias for the variable name.
From the Cocoa Fundamentals Guide:
The syntax for
@synthesize
also includes an extension that allows you to use different names for the property and its instance-variable storage. Consider, for example, the following statement:
@synthesize title, directReports, role = jobDescrip;
This tells the computer to synthesize accessor methods for properties
title
,directReports
, androle
, and to use thejobDescrip
instance variable to back therole
property.
Upvotes: 2