Rob
Rob

Reputation: 780

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?

Upvotes: 5

Views: 639

Answers (5)

Joao Henrique
Joao Henrique

Reputation: 587

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.

Upvotes: 1

Williham Totland
Williham Totland

Reputation: 29029

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.

Upvotes: 4

Rengers
Rengers

Reputation: 15238

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

Upvotes: 1

CVertex
CVertex

Reputation: 18237

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

Upvotes: 0

mipadi
mipadi

Reputation: 411142

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]

Upvotes: 3

Related Questions