开发者

Underscore prefix on property name? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How does an underscore in front of a variable in a cocoa objective-c class work?

Can anyone point me to an explanation of the use of underscores, I have always assumed that they are used to highlight that you are accessing the iVar [_window release]; rather than accessing the iVar via a setter/getter method [[self window] release]; o开发者_Python百科r [self.window release]; I just want to verify that my understanding is correct.

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UILabel *markerLabel;

@synthesize window = _window;
@synthesize markerLabel = _markerLabel;


The use of an underscore for ivar names is a convention first used by Apple to differentiate between an actual ivar and a property. Many people have since adopted this convention.

The reason this is done is to prevent the mistake of assigning a new value to an ivar instead of to the actual setter:

myIvar = newValue;

instead of

self.myIvar = myValue;

If you accidentally use the top example, you could cause a memory leak. The underscore prevents you from making that mistake.


It's a convention, and your understanding sounds fine.

Another merit of this convention is that you can't accidentally access the ivar without using the setter, because

view = viewController.view ; // usually bad

will not compile if the ivar is _view instead of view.

I usually don't declare the ivar, though, and just use @property and @synthesize. Without an explicit ivar declared, the compiler (at least a recent one) automatically generates the ivar (with the same name.) So the code above compiles without problem, and doesn't serve as a guard against not using the setter, but you can do away with one line of code.... which might be a bad thing to aim for and I don't recommend it to you :p

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜