Underscore prefix on property name?

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.

  • get UDID of IOS device programmatically?
  • CFBundleVersion in the Info.plist Upload Error
  • Too many arguments to method call
  • Is there a way to specify argument position/index in NSString stringWithFormat?
  • Facebook is not shown in UIActivityViewController but twitter does
  • UIWebView not go to didFailLoadWithError when webLink not found?
  • @property (nonatomic, retain) IBOutlet UIWindow *window;
    @property (nonatomic, retain) IBOutlet UILabel *markerLabel;
    
    @synthesize window = _window;
    @synthesize markerLabel = _markerLabel;
    

    2 Solutions Collect From Internet About “Underscore prefix on property name?”

    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