I’ve got a doubt about assigning values to properties in Objective-C. I’ve had a lot of problems of “misteriously missed” values, for example if I have this interface:
// MyClass.h
@interface MyClass : NSObject {
MyOtherClass *myVar;
}
@property (nonatomic, retain) MyOtherClass *myVar;
- (id)initWithValue:(NSString *)val;
And this implementation:
// MyClass.m
@implementation MyClass
@synthesize myVar;
- (id)initWithValue:(NSString *)val {
self = [super init];
if (self != nil) {
/** Do some stuff with val... **/
myVar = [method:val]; // Some method that returns a MyOtherClass value
}
return self;
}
At some point of the execution, the value of myVar disappears, changes or something else… And the solution is to change:
myVar = [method:val]; // Some method that returns a MyOtherClass value
for
self.myVar = [method:val]; // Some method that returns a MyOtherClass value
So… what is the diference between using self or not using it? I mean, it’s clear that I’ve to use it because if not it will cause problems but I don’t know why
Thank you in advance
This is a good example of why you should change your
@synthesizeto@synthesize myVar = _myVar;or some variation of that. Without doing that, it is possible to set your instance variable out from under you as a direct assignment of `myVar = nil” would bypass your setter.Using the
myVar = _myVarstrategy will cause the compiler to complain if you attempt to domyVar =and will require you to callself.myVarwhich will access your setter or getter.The only place you should then use
_myVaris if you change the declaration of your setter or getter for that variable.