6

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?

Rob
  • 792
  • 2
  • 7
  • 15

5 Answers5

5

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.

Williham Totland
  • 28,471
  • 6
  • 52
  • 68
  • What if I use message notation rather than dot notation? Does it matter? – Rob May 07 '10 at 13:52
  • really CLEAR answer, because in many tutorials in web all say that is the same things, thanks for answer – hbk Sep 09 '14 at 10:06
3

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]
mipadi
  • 398,885
  • 90
  • 523
  • 479
  • 2
    When assigning to instance variable, it's necessary to use self if you are relying on the setter to do copy or retain. – David Gelhar May 07 '10 at 13:56
1

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
Rengers
  • 14,911
  • 1
  • 36
  • 54
  • Note that you don't have to use the dot-notation. But a lot of us like it. I caution you though: dot-notation almost looks like you are accessing a field from a non-pointer struct, as opposed to sending a message to an object. Because Objective-C objects are pointers to structs, `self.someiVar = @"this"` cannot access an instance variable; you would use `self->someiVar = @"this"` (the `self->` bit is unnecessary within the implementation of a class). So, use dot-notation if you understand what you're doing, and what you're not doing. – Jonathan Sterling May 07 '10 at 13:54
1

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.

Joao Henrique
  • 547
  • 5
  • 13
0

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

CVertex
  • 17,997
  • 28
  • 94
  • 124