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?
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
.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With