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?
ageandself.ageare 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 whyageworks 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,ageandself->ageare exactly the same thing, butself.ageis completely different.