3

Possible Duplicate:
Should I Use self Keyword (Properties) In The Implementation?

Say I have a class "Person", with an instance variable "age". Coming from Python, when writing methods for the Person class, I am used to accessing age using "self.age", however in Objective C I have noticed that both and "self.age" and "age" are accepted when referring to the instance variable (whereas in Python only the former would work).

When it is not explicitly specified which instance's variable you mean, does it default to 'self'? And is it considered bad style not to explicitly specify self? If not, are there conventions on when to use self.age and when to use age?

Community
  • 1
  • 1
Timo Vink
  • 65
  • 2
  • 1
    Already explained here http://stackoverflow.com/questions/1051543/should-i-use-self-keyword-properties-in-the-implementation – Henrik P. Hessel May 16 '11 at 22:11
  • Guido likes "explicit" reference to member variables, so he decided they should all be written `self.ivar` Objective-C has a separate namespace for ivars and method names, and there's a new syntactical element using "properties", where `self.ivar` actually is sugar for a method call. To do a simple access of an ivar in ObjC, you write the bare ivar name. The dot syntax would actually be illegal unless you were using a property, because `self` is a pointer and Obj-C is C, blah blah blah. (See ughoavgfhw's answer) :) Please see the link Henrik found. – jscs May 16 '11 at 22:15

2 Answers2

3

age and self.age are two completely different things. Inside of instance methods, the object's instance variables are implicitly defined in the scope, unless shadowed by a local variable (See The Objective-C Programming Language). That is why age works correctly. When using the dot notation, you are referencing a property, which means you are actually calling [self age] instead of directly accessing the instance variable. You can also access an instance variable directly by using the structure pointer operator (->). This is rarely used, but can be used to directly access variables in other instances of the same class or different classes, as well as self. Therefore, age and self->age are exactly the same thing, but self.age is completely different.

ughoavgfhw
  • 39,734
  • 6
  • 101
  • 123
0

Using self uses the accessor and mutator methods, while leaving it out modifies the instance variable directly. In order to use self.age, you must have age declared as a property with the @property syntax. I typically try to use self wherever I can.

Adrian Sarli
  • 2,286
  • 3
  • 20
  • 31