Underscore prefix on property name? [duplicate]
Asked Answered
O

2

11

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]; or [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;
Oscaroscillate answered 7/4, 2011 at 14:7 Comment(1)
This used to point to this other dupe here, which is interesting too #3521754Skricki
D
11

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.

Deductive answered 7/4, 2011 at 14:16 Comment(1)
Was it really used by Apple? In any case, Apple doesn't use this convention. It is neither mentioned in the Cocoa Coding Guidelines nor used in Apple's own code, for example: developer.apple.com/library/mac/#samplecode/TreeView/Listings/… The underscore does not prevent you from making the mistake of using the property where you meant to use the instance variable.Emeldaemelen
M
0

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

Morissa answered 7/4, 2011 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.