Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "self" necessary?

Is using "self" ever necessary in Objective-C or maybe just a good practice? I have gone from using it all the time to not using it at all and I don't seem to really notice any difference. Isn't it just implied anyway?

like image 673
Rob Avatar asked May 07 '10 13:05

Rob


3 Answers

self is necessary if you wish for an object to send messages to, well, itself. It is also occasionally beneficial to access properties through getters/setters, in which case you'll also need to use self, as in self.propertyname or self.propertyname = value. (These are not equivalent to propertyname or propertyname = value.

like image 83
Williham Totland Avatar answered Nov 05 '22 12:11

Williham Totland


It's not necessary when referring to instance variables. It is necessary when you want to pass a reference of the current object to another method, like when setting a delegate:

[someObj setDelegate:self];

It's also necessary when calling a method in the same class on the current object:

[self doMethod]
like image 20
mipadi Avatar answered Nov 05 '22 12:11

mipadi


For dealing with variables it depends. If you want to use a synthesized getter or setter, use the dot notation with self.

self.someProperty = @"blah"; //Uses the setter
someProperty = @"blah"; //Directly sets the variable
like image 31
Rengers Avatar answered Nov 05 '22 10:11

Rengers