It's a month ago I was reading a line about that. I am not sure, but I think that if I call self.myInstanceVariable then it uses automatically getters/setters, but if I would call directly myInstanceVariable = @"Foo" for example, then I would bypass any getter/setter which would be really, really, reeeaaallly bad. Right/wrong?
EDIT: I tried this in XCode.
The implementation looks like this:
@implementation Test
@synthesize name;
+ (Test*)testWithName:(NSString*)name {
Test* test = [self alloc];
test.name = name;
return [test autorelease];
}
- (void)setName:(NSString*)newName {
NSLog(@"SETTER CALLED!!");
if(name != newName) {
[name release];
name = [newName retain];
}
}
- (NSString*)name {
NSLog(@"GETTER CALLED!!");
return name;
}
- (void)doWrongThing {
NSString *x = name;
NSLog(@"doWrongThing: %@", x);
}
- (void)doRightThing {
NSString *x = self.name;
NSLog(@"doRightThing: %@", x);
}
The test code looks like that:
Test *t = [Test testWithName:@"Swanzus Longus"];
//NSLog(@"%@", t.name);
[t doWrongThing];
[t doWrongThing];
[t doWrongThing];
[t doRightThing];
So after launching this code in another method (I just used an existing project ;) ), I received this output in the console:
2009-05-01 19:00:13.435 Demo[5909:20b] SETTER CALLED!!
2009-05-01 20:19:37.948 Demo[6167:20b] doWrongThing: Swanzus Longus
2009-05-01 20:19:37.949 Demo[6167:20b] doWrongThing: Swanzus Longus
2009-05-01 20:19:37.949 Demo[6167:20b] doWrongThing: Swanzus Longus
2009-05-01 20:19:37.950 Demo[6167:20b] GETTER CALLED!!
2009-05-01 20:19:37.965 Demo[6167:20b] doRightThing: Swanzus Longus
Like you see, you MUST use self.instanceVariableName in order to use the getters and setters (or you do the call in brackets, works too).
Confusion Alert: You must only use self if you hack around in a method of the object from which you want to access an instance variable. From the outside, when you call someObjectPointer.someInstanceVariable, it will automatically access the getters and setters (yep, I tried that out too).
Just thought someone would be interested in a little case study ;)