Reputation: 6125
I have cocos2d class which produces memory leak if I do not release autoreleased object (self.graphicsContainer). Code:
@property (nonatomic, retain) CCNode * graphicsContainer; // I create property
@synthesize graphicsContainer = _graphicsContainer; // I synthesize it
-(id)init
{
if ((self = [super init])) {
self.graphicsContainer = [CCNode node]; // which returns autoreleased object!
}
return self;
}
-(void) dealloc
{
[self.graphicsContainer release]; // If I do not release it I get memory leak warning!
[super dealloc];
}
Anyone knows why I have to release it? As far as I know I shouldn't release autoreleased objects?
Upvotes: 0
Views: 588
Reputation: 17898
That's exactly the behavior I'd expect from that code. Because graphicsContainer is a retained property, the line
self.graphicsContainer = [CCNode node]; // which returns autoreleased object!
...will retain the the node, so you need to release it in dealloc as you're doing. There's basically nothing wrong with what you're doing there.
One caveat: it's perhaps controversial, but for various reasons, it's generally frowned upon to use property accessors in init and dealloc. This SO question has more information on that (even better: read Mike Ash's excellent analysis of the subject).
If you fall into the 'property accessors in init/dealloc is bad' camp (I do), you could change it to this:
-(id)init
{
if ((self = [super init])) {
_graphicsContainer = [[CCNode node] retain]; // which returns autoreleased object!
}
return self;
}
-(void) dealloc
{
[_graphicsContainer release];
[super dealloc];
}
The code above is exactly equivalent to what you're doing, except that it's not calling the property accessors.
Upvotes: 1