Reputation: 3629
In Objective C what scenario would I want to use [self setVariable:value];
instead of variable = value;
It seems as if doing a self set I'm saving myself few lines of code, but what other advantages are there? Additionally, when would I NOT want to do a self set?
Upvotes: 2
Views: 280
Reputation: 17732
EDIT:
I should clarify, that what I am referencing below is strictly in regards to variables that are properties. If a variable is just an ivar, then there is no difference between self.variable = value
or variable = value
, other than the fact that self.variable = value
will not even compile if it is just an ivar, in that case you need to use self->variable = value
Calling
[self setVariable:value];
is the same as calling
self.variable = value;
This, however, is NOT the same as
variable = value;
The first two cases use the synthesized setVariable
method (or the one you defined yourself). The reason you would want to use this is to make sure you keep the proper retain count on your objects.
For example, a simple property such as:
@property (retain) NSString *myString;
Gets an automatically generated set function that looks something like:
-(void) setMyString:(NSString*)other
{
myString = [other retain];
}
If you were to just call
myString = otherString;
elsewhere in your code, then myString
is not retained properly, so if otherString
gets deallocated, your pointer to that object is no longer valid.
Upvotes: 3
Reputation: 122391
You definitely need to use it when holding objects that require retaining and releasing in order to conform to the Objective-C memory management model. For example:
MyObject.h:
@interface MyObject : NSObject
{
NSString *_name;
}
@property (retain, nonatomic, readwrite) NSString *name;
@end
MyObject.m:
@implementation MyObject
@synthesize name = _name;
- (id)init
{
self = [super init];
if (self != nil)
{
self.name = [NSString stringWithFormat:@"name:%d", 12];
}
return self;
}
- (void)dealloc
{
self.name = nil;
[super dealloc];
}
@end
For data types like int
, float
, etc., that don't require memory management you can get away without using the setter/getter methods, however it's good practice to use them all the time.
Upvotes: 0
Reputation: 11839
The main reason of using setter over assigning value to variable is to achieve Encapsulation.
Some Benefits are -
Upvotes: 1