Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between calling self.myInstanceVariable and directly myInstanceVariable?

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 ;)

like image 616
Thanks Avatar asked May 24 '26 23:05

Thanks


1 Answers

That is correct. If you directly use the variable, bypassing the getter/setter you could create bugs. The getter/setter may be responsible for retain and/or releasing the object as well as other things. This could result in crashes/memory leaks etc.

If you are aware that you are bypassing the getter/setter and take the right precautions, there is nothing wrong with accessing the variable directly.

like image 126
Jab Avatar answered May 27 '26 12:05

Jab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!