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
}
_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.
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.
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.