I was told by a fellow StackOverflow user that I should not use the getter method when releasing a property:
@property(nonatmic, retain) Type* variable;
@synthesize variable;
// wrong
[self.variable release];
// right
[variable release];
He did not explain in detail why. They appear the same to me. My iOS book said the getter on a property will look like this:
- (id)variable {
return variable;
}
So doesn't this mean [self variable]
, self.variable
, and variable
are all the same?
The NSArray class method array returns a newly initialized array that is already set for autorelease. The object can be used throughout the method, and its release is handled when the autorelease pool drains. At the end of this method, the autoreleased array can return to the general memory pool.
Properties in Objective-C allow you to provide a well-defined interface for other classes to manipulate (i.e. get or set) attributes of a class. They also insulate external classes from the implementation details of the attributes (this separation of function and implementation is known as encapsulation).
For a retained property with no custom accessor, you can release the object by:
self.variable = nil;
This has the effect of setting the ivar (which may not be called 'variable' if you have only declared properties) to nil and releasing the previous value.
As others have pointed out, either directly releasing the ivar (if available) or using the method above is OK - what you must not do is call release on the variable returned from a getter.
You can optionally write custom getter behavior, which may result in completely different behavior. So, you cannot always assume that [variable release]
has the same results as [self.variable release]
.
As well, you can write custom properties without an exclusive ivar backing them... it can get messy fast if you start releasing objects from references returned by getters!
There may be additional reasons that I'm unaware of...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With