Possible Duplicate:
Difference between class property mVar and instance variable self.mVar
I am new to developing in Objective-C and I couldn’t quite figure out what the difference is between the following:
First let me explain my situation. I’ve got an NSMutableArray, and I created and outlet for it in my .h file. Now when I assign an array to it as
self.myMutableArray=myArray
I get an error; However just
myMutableArray=myArray
works fine.
I am not interested in the resolving of the error. I just want to know what is the difference when putting self in front of something? And why I am able to use the variable also without self and what restrictions that brings with it?
is equal to:
That is to say, the declaration using
self.goes through the object’s accessor method, rather than using direct access.They have different causes and effects. Perhaps the most notable is that direct access will often leads to reference count issues (leaks/zombies) if not used with care. The accessor is responsible for handling memory management – if synthesised, or if you implement it yourself.
The General Rule: You should favor using the accessors (
self.blah = thing;) over direct access (blah = thing;) until you know when and why you would make exceptions to this rule.The immediate exception: There is one exception to the general rule: Do not use the accessors in partially constructed states, such as the object’s initializer or
dealloc. In those cases, use direct access:Update
Describing Bavarious’ suspicion of the error:
It sounds like you have declared an instance variable, but have not declared an associated property or proper accessors (e.g. the setter). Here’s a breakdown of a class’ declaration with ivars and properties: