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开发者_StackOverflow'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
Actualy it is not necessary every time,but it is a good practice, because it makes it easier for other people to read your code.
And it is necessary when you have objects with the same name in different classes, then the "self" keywork will tell your software that you are referencing the object in that same class.
That usually happends in bigger projects.
Yes, because Objective C doesn't have method calls like C/C++ but uses message sending, self for in contexts like
[self doSomething]; and self.myProperty;
are necessary.
If you are accessing an ivar, self is not needed.
Hope that helps.
-CV
精彩评论