hello a noob question here.
during my studies I was repeatedly instructed to always specify a =_propertyName variable when @synthesize-ing a @property
so for example for
@property (nonatomic, strong) NSTimer *myTimer;
I would do
@synthesize myTimer = _myTimer;
now my question is. does this have to be done for IB properties as well ?
such as
@property (nonatomic, strong) IBOutlet UILabel *myLabel;
@property (nonatomic, strong) IBOutlet UIButton *myButton;
do I just do here:
@synthesize myLabel;
@synthesize myButton;
or:
@synthesize myLabel= _myLabel;
@synthesize myButton = _myButton;
Now I can see, why this is useful for something like an NSArray, or NSString or BOOL where you’re actually storing some values, but I am not sure how/if this logic applies to UIButtons, UILabels and similar. Thank you for any pointers (no put intended)
It is a matter of preference. There is a difference that you should keep in mind, however, as far as scope. For example, if you write your synthesizer like this,
And you are within the scope of an instance method of the class, for example,
-(void)setTime:(id)myTime;, there is a difference between calling,And,
It becomes clear that the first changes the instance variable of your object, and that the second reassigns the
myTimelocal variable passed in as an argument to the methodsetTime:, which is something you usually don’t want to do. However, if you synthesized your instance variable like this,It is a little more confusing what would happen with this assignment,
This actually reassigns the local variable, and may not be what you intended. So in naming your variables it is good to stick to conventions and try to avoid confusion. That is why it is my personal preference to assign the underscore and always set instance variables by calling them attached to
self.