-1

I am new to iOS development. I am creating a simple app that calculates the payout of a horse bet based on the user's bet placed and the odds they enter for the horse. In XCode (4.6.3), I have the following method which is used to calculate increase the user's bet by 1 when the button is clicked:

-(IBAction) addBet:(id) sender {
    self.bet = [_betTextField.text intValue];
    if(self.bet > 0) {
        self.bet += 1;
        self.betTextField.text = [NSString stringWithFormat:@"%d", self.bet];

    }
}

I have declared the betTextField variable as follows in my header file: @property (weak, nonatomic) IBOutlet UITextField *betTextField; XCode gives me an error if I do not use the underscore before the betTextField.text variable. Why is this?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
JT9
  • 914
  • 5
  • 13
  • 22
  • Because the naming convention for automatic property synthesis is designed and implemented like so. –  Aug 03 '13 at 16:38
  • 3
    And here's another 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 Aug 03 '13 at 19:13

2 Answers2

4

The purpose of the underscore is to make it so that you can't accidentally use the ivar directly when you meant to use the property instead.

Catfish_Man
  • 41,261
  • 11
  • 67
  • 84
1

Because without the underscore the name doesn't really exist. This is because of what @property means and what the compiler does for you behind the scenes. Basically, your property can be accessed by using self.betTextField (which uses the automatically defined accessor methods) or _betTextField (which directly accesses the instance variable).

Wain
  • 118,658
  • 15
  • 128
  • 151