0

Possible Duplicate:
How does an underscore in front of a variable in a cocoa objective-c class work?
Prefixing property names with an underscore in Objective C

When we declare a property and then synthesize it like this for example: @synthesize name = _name; So, the _name is an instance variable for the name property we are gonna use in the following implementation. My question is why we need this ivar and what would happen if i didn't create the _name ivar? Thank you.

Community
  • 1
  • 1
dsfdf
  • 106
  • 2
  • 7
  • 1
    And here's the other 16: http://stackoverflow.com/q/5582448/ http://stackoverflow.com/q/6049269/ http://stackoverflow.com/q/2371489/ http://stackoverflow.com/q/7174277/ http://stackoverflow.com/q/5659156 http://stackoverflow.com/q/837559/ http://stackoverflow.com/q/6146244/ http://stackoverflow.com/q/10651535/ http://stackoverflow.com/q/6124109/ http://stackoverflow.com/q/8145373/ http://stackoverflow.com/q/3521254/ http://stackoverflow.com/q/6064283/ http://stackoverflow.com/q/9696359/ http://stackoverflow.com/q/5521499/ http://stackoverflow.com/q/5466496/ http://stackoverflow.com/q/2114587/ – jscs Jun 21 '12 at 18:05

1 Answers1

0

My understanding is that there is a default ivar name, which is the same as the property name. One of the reasons for specifying your own, with an underscore, is to eliminate ambiguity in your setter:

-(void) setFoo:(id) foo {
  // here, foo should ONLY refer to the passed-in var
  // If your ivar is the same, it is ambiguous.
  // If your ivar is _foo, then there is clarity.
}
Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
  • oh,i see. So like in java, it will be like this: this.name = name,in order to make it clear that the right hand-sided name is the argument, but in here we just use _name to distinguish this,right? – dsfdf Jun 21 '12 at 15:30
  • Yeah, in some languages you must use `this` or `self` or something to access instance variables, but not in Objective-C. It may appear as though self.name is the same as just saying name, but the two are really very different. self.name *sends a message* (it is virtually identical to [self name]). just using name is directly using a variable. – Chris Trahey Jun 21 '12 at 15:57