问题
Can someone explain to me the significance of creating (what seems to be) an extra variable and why put an underscore before a new variable with the same name as the last.
I have read that it is to do with creating instance variables but why would you want to create a UI element as an instance variable? Can you please provide a use case?
This objective c code for use in iOS development.
Thanks.
回答1:
When you @synthesize
a property and you do not provide your own getter and setter methods (in which case there is no need to @synthesize
) then there is always a new instance variable created. By default it gets the same name as the property. So @synthesize slider;
makes an instance variable named slider
behind the scenes.
The problem here is that you might mistakenly type slider = xxx
when you really meant to use self.slider = xxx
. When you make something a property, best practice says you should always access it through self.propertyName
(except in your init and dealloc methods and any custom getter and setter methods).
So in order to avoid this, the @synthesize
statement is used to rename the backing ivar into something that is harder to confuse with the property. If you now use slider
instead of self.slider
the compiler will give an error message because slider
is no longer the name of an instance variable.
回答2:
The reason for doing that is to make the instance variable clearly stand out from the property dotting syntax. It also has the practical effect of avoiding shadowing of instance variables from argument names, which also occur in some situations.
The reason for using an instance variable at all is in most cases to avoid KVO triggering in dealloc. If you do this, you risk triggering KVO in such a way that your observers gets a deallocated object passed to them, causing an EXC_BAD_ACCESS.
- (void)dealloc
{
self.slider = nil;
[super dealloc];
}
So it's common to do this instead, which will not trigger KVO since you don't do property access.
- (void)dealloc
{
[_slider release];
[super dealloc];
}
回答3:
This is commonly used to synthesize the property to a private prefixed or suffixed ivar. It tries to prevent you from accidentally accessing the ivar and not the property or overriding the ivar with a method argument.
Consider this:
@implementation MYClass
@synthesize flag = flag_;
- (void)doSomethingWithFlag:(BOOL)flag {
if (flag) {
// You do not need to worry about confusing the ivar
// flag and the param flag because it is synthesized to flag_
}
}
- (void)doSomething {
if (flag) { // Doesn't work -> use accessor self.flag
...
}
}
@end
来源:https://stackoverflow.com/questions/7724249/what-is-the-point-of-calling-synthesize-slider-slider