I am trying to get more into detail with Objective-C programming language.
Right now I have a question regarding calling [self] when setting values.
The Apple documentation says “If you do not use self., you access the instance variable directly. (…)”
So assuming I have a dog object that has an instance variable NSString *name.
I create a setter for that instance variable like this without using the [self] keyword:
(void)setName:(NSString *)_name
{
name = _name;
}
When I alternatively create a setter WITH the [self] keyword it looks like this:
(void)setName:(NSString *)_name
{
self->name = _name;
}
In the main-method I create a new dog object and set and return its name value:
Dog *myDog = [[Dog alloc] init];
myDog.name = @"Yoda";
NSLog(@"name of the dog: %@", myDog.name);
In both cases I get a return value of Yoda. But where is the difference between an instance variable call with and without [self] technically? Is it that I call the same variable (memory) just without using the setter method?
selfis an implicit reference to the object itself, and generally you only really need to specify it when a parameter and an instance variable have the same name, for example if you had:However, you need to be careful with your naming conventions and implementation of methods:
NSString *object, generally you are going to need toretainit in order to take ownership of the object and to avoid it getting released (which will cause an exception when you access it later).Therefore your
setNamemethod should look more like this:This is only true if you are using MRR, instead of ARC, but you don’t specify that so I’ll assume you are using MRR.