Reputation: 33036
I know that you use @synthesize to create setter and getter methods, which makes things easier because then you don't have to write your own.
There are certain places where you have to use self.property instead of just property in order to make use of the setter and getter methods, such as in dealloc and initWithCoder.
This tells me that these setter and getter methods are doing something else that's important, besides making it easier for you to set and get a variable. What are they doing and how do they do it?
Upvotes: 1
Views: 1572
Reputation: 225162
They're doing whatever you told them to do in the @property
statement or your own implementation, if you chose to write one. Most often, the reason for using the accessors rather than directly modifying instance variables is to avoid memory leaks. Imagine an NSString
instance variable declared with
@property (nonatomic, retain) NSString *myString;
@synthesize myString;
These lines generate an accessor that correctly calls release
and retain
when you want to change the myString
property of an object. If you didn't call the accessor, you could potentially leak the old value, unless you were careful to do the memory management yourself.
Upvotes: 5
Reputation: 9364
I second what @heckj and @Carl said, but must add one more point.
In general it is not safe to use accessors in either init
or dealloc
. The problem is that you class might be subclassed, the accessors might be overridden. Then these accessors might access other properties of your class or a subclass. This might lead to crashes:
init
these haven't been initialized yet (because in init
the first call you do is [super init]
).dealloc
these have already been freed (because in dealloc
the last call you do is [super dealloc]
).In practice you may use accessors in init
and dealloc
. Under two premisses:
Upvotes: 2
Reputation: 7367
Your base precept:
There are certain places where you have to use self.property instead of just property in order to make use of the setter and getter methods, such as in dealloc and initWithCoder.
This tells me that these setter and getter methods are doing something else that's important...
isn't quite correct. The difference here is that using self.propertyname specifically invokes the getter/setter when used within that class, where directly using propertyname doesn't - it accesses the instance variables directly.
Per @Carl Good practice is that you use the getter/setter sequence everywhere you absolutely can, as that keeps you pretty safe from missing a corner case of memory management.
Upvotes: 3