Note that there are some explanatory texts on larger screens.

plurals
  1. POI’ve set my property to retain, am I supposed to release it even if it is set to autorelease?
    text
    copied!<p>Let us say we have some code that looks like below:</p> <pre><code>@interface SomeClass : NSObject @property (nonatomic, retain) NSString *someString; @end @implementation SomeClass @synthesize someString; -(id)init { if (self=[super init]) { someString = [NSString stringWithString:@"some string"]; } return self; } @end </code></pre> <p>Am I supposed to release the <code>someString</code> property in the dealloc method of <code>SomeClass</code>, even if <code>someString</code> was set to autorelease and I never actually retained it in my <code>init</code> method? If so, I'd simply add <code>[someString release]</code> before <code>[super dealloc]</code> in the <code>-release</code> method. Correct?</p> <p>Now the real issue I am having is that while using Cocos2D, I've reached a contradicting situation. My code looks like below:</p> <pre><code>@interface SomeLayer : CCLayer @property (nonatomic, retain) CCSprite *someSprite; @end @implementation SomeLayer @synthesize someSprite; -(id)init { if (self=[super init]) { someSprite = [CCSprite spriteWithFile:@"SomeFile.png"]; [self addChild:someSprite]; } return self; } @end </code></pre> <p>Now, I have added <code>someSprite</code> as a child to my layer <code>SomeLayer</code>. So, what should I do to make sure I have no memory leaks here? I could think of the following:</p> <ol> <li>Obviously, I'd think of calling <code>[someSprite release]</code> in <code>SomeLayer</code>'s <code>-dealloc</code> method. but it gives me <code>EXC_BAD_ACCESS</code> in <code>[super dealloc]</code> (the next line). Most likely because I didn't remove the child, and the superclass tries to access the child that I just released.</li> <li>I call <code>[self removeChild:someSprite cleanup:YES]</code> in the <code>-dealloc</code> method, which would remove the child and also release it. So I do not need to follow up with <code>[someSprite release]</code>. But hey, the <code>-dealloc</code> method of the superclass <code>CCNode</code> already does all that for me.</li> <li>I do nothing. I wouldn't override the <code>-dealloc</code> method at all. Well, this seems to work fine, but it contradicts the statement: "if you retain something, you're supposed to release it".</li> </ol> <p>Any help on why I must release the object in case I, and why not in case II at an early stage would help save a lot of memory related issues in the long run.</p> <p>Thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload