20

Possible Duplicate:
Underscore prefix on property name?

What does this mean? @synthesize window=_window; I know that in general it means that 'some class' has a window, but why use _window instead of just window? Is this a namespace thing?

Community
  • 1
  • 1
lampShade
  • 4,361
  • 8
  • 34
  • 50
  • check out this related question: http://stackoverflow.com/questions/3521254/prefixing-property-names-with-an-underscore-in-objective-c – filipe May 18 '11 at 18:24
  • 2
    Duplicates: [1](http://stackoverflow.com/questions/3521254) [2](http://stackoverflow.com/questions/822487/) [3](http://stackoverflow.com/questions/2371489) [4](http://stackoverflow.com/questions/5582448/) [5](http://stackoverflow.com/questions/837559/) [and so on...](http://stackoverflow.com/search?q=objc+property+underscore) – jscs May 18 '11 at 21:08

3 Answers3

25

I'll give a go at describing this programming convention in basic English.

It is a very common convention in other languages to name member variables with a preceding m, m_, or _ to distinguish them from locally declared variables and to signify that they should have accessors written, if necessary (no classInstance.m_Variable = 5).

If an Objective-C programmer declares ivars following this convention (and they should) and uses the basic syntax @synthesize _window; then the usage for the property becomes somewhat ugly: classInstance._window = myWindow or [classInstance set_window:myWindow]. Using the syntax @synthesize window=_window; allows the Obj-C programmer to utilize a popular programming standard (preceding ivars with _) while simultaneously having property accessors that use the Apple standard classInstance.window = myWindow and [classInstance setWindow:myWindow].

Thomson Comer
  • 3,919
  • 3
  • 30
  • 32
4

This is a very common thing to do in iOS programming/objective-C, it has to do with ivars. For more information you can read here:

Why rename synthesized properties in iOS with leading underscores?

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

Based on my experience in having this habit in my code, it helps me to accidentally writing window when you mean self.window and vice-versa (doesn't have to be window, but any other variables as well)

Community
  • 1
  • 1
aherlambang
  • 14,290
  • 50
  • 150
  • 253
3

short answer is: the underscore is just a convention useful to stress the fact that class variables are "private" to a class and you should access them via their properties.

you could declare your window variable without the leading underscore; in this case the @synthetize statement would be simply: @synthetize window, and it would be practically the same.

for the long answer, the links posted by aherlambang are really interesting read...

sergio
  • 68,819
  • 11
  • 102
  • 123