3

I'm slightly confused as to the proper conventions when dealing with properties. I'll illustrate my question through an example. So from the example below I know that functionally "self.loan = self.loan + 250.00;" is the same as "_loan = _loan + 250.00;" or is it not? I see numerous tutorials all over the web that may or may not use both methods to access a property. So what exactly is the difference between using _loan and self.loan (I know that self.loan is the same as [self setLoan:])

//ClassA.h
@interface ClassA: UIViewController
@property double loan;
@end

//ClassA.m
@implementation ClassA
@synthesize loan = _loan;

-(void)doSomething{
  self.loan = self.loan + 250.00; //Exhibit A
  _loan = _loan + 250.00; // Exhibit B 
} 
SNV7
  • 2,563
  • 5
  • 25
  • 37
  • 2
    Mark Dalrymple of Big Nerd Ranch wrote [a great article about this very topic](http://weblog.bignerdranch.com/463-a-motivation-for-ivar-decorations/). Doing what he does it almost never a bad idea. – SSteve Jun 04 '12 at 22:38
  • possible duplicate of [iPhone different between self and normal variable](http://stackoverflow.com/questions/536388/iphone-different-between-self-and-normal-variable) – jscs Jun 05 '12 at 00:53
  • possible duplicate of 500 prior threads. – Hot Licks Jun 05 '12 at 02:55

3 Answers3

5

_loan is a variable and assigning a value to it has no particular side effect.

self.loan = self.loan + 250.00 is essentially the same as writing [self setLoan:[self loan] + 250.00] in that methods are called that may do other things than simply set or get the value of a variable. The extra things those methods do depend on whether you write custom versions of them (the setters and the getters) or use @synthesize to create them and, if you use @synthesize, what attributes you apply in the @property declaration.

Miguel-F
  • 13,450
  • 6
  • 38
  • 63
Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
0

When you write out @synthesize loan = _loan; it is basically shorthand to say that what you are synthesizing is = to a private member it would be similar to the verbose way of coding it below:

//ClassA.h
@interface ClassA: UIViewController {
    double _loan;
}

@property double loan;
@end

//ClassA.m
@implementation ClassA
@synthesize loan = _loan;

It is good practice to write it out this way so you can clearly have a '_' to signify your private members within your class code but when exposing this as a property to other classes that shouldn't be shown.

rooster117
  • 5,502
  • 1
  • 21
  • 19
-1

You should never use direct reference to a variable when accessing a property. Always go for self.property in your code.

If you use _property you are not making use for your getters and setters. In this case you are just wasting @synthesize use.

self.loan = self.loan + 250.00; //Exhibit A

This should be right approach.