If I declare an ivar without property declaration, and this ivar could be used or not during the object life-cycle, do I have to release it in dealloc?
I have sometimes seen that properties are declared as ivar and property, and sometimes only have property declaration. What is the difference? Which is the better way?
Example:
@interface MyClass: NSObject
{
NSObject *ivar; // This is sometimes omitted.
}
@property (nonatomic, retain) NSObject *ivar;
@implementation MyClass
@synthesize ivar;
...
-(void)dealloc
{
[ivar release];
[super dealloc];
}
How come the ivar declaration is sometimes omitted?
The other case is when there is no property declaration:
@interface MyClass: NSObject
{
NSObject *ivar;
}
@implementation MyClass
-(void)thisMethodCanBeCalledOrNot
{
ivar = [[NSObject alloc] init];
[ivar useIt];
//ivar must be alive for further uses in different methods of this class. For this is not released in this method.
}
...
-(void)dealloc
{
[ivar release]; //If thisMethodCanBeCalledOrNot is never called, could this cause a over release in ivar?
[super dealloc];
}
Yes you have to release it. When you call
[ivar release], nothing happens if the ivar isnil, but if it contains a pointer to an object, you would cause a memory leak by not releasing it.It’s preferable to not use
self.ivar = nilin thedeallocmethod, as the setter method could contain logic that is unnecessary during deallocation, or could even cause tricky bugs.Regarding
@propertydeclarations without an explicit ivar declaration, the “modern runtime” synthesizes the ivar automatically.