Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore prefix on property name? [duplicate]

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;
like image 352
fuzzygoat Avatar asked Apr 07 '11 14:04

fuzzygoat


People also ask

What is prefix with underscore?

The underscore prefix is meant as a hint to another programmer that a variable or method starting with a single underscore is intended for internal use. This convention is defined in PEP 8.

What does an underscore in front of a variable name mean?

A single leading underscore in front of a variable, a function, or a method name means that these objects are used internally.

What does an underscore before a property name indicate in JavaScript?

Underscore ( _ ) is just a plain valid character for variable/function name, it does not bring any additional feature. However, it is a good convention to use underscore to mark variable/function as private. You can check Underscore prefix for property and method names in JavaScript for some previous discussion.

Can you use underscores in variable names?

Variable names should not start with underscore ( _ ) or dollar sign ( $ ) characters, even though both are allowed. This is in contrast to other coding conventions that state that underscores should be used to prefix all instance variables.


1 Answers

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.

like image 69
voidzm Avatar answered Nov 08 '22 17:11

voidzm