1

having a look at the following code:

    CCSprite* testsprite = [CCSprite spriteWithFile:@"test.png"];
    CCLOG(@"1. count: %d", [testsprite retainCount]);
    [self addChild:testsprite];
    CCLOG(@"2. count: %d", [testsprite retainCount]);
    [testsprite runAction: [CCMoveTo actionWithDuration:3.0 position:CGPointMake(200.0, 200.0)]];
    CCLOG(@"3. count: %d", [testsprite retainCount]);

the output of this code is:

1. count: 1
2. count: 2
3. count: 3

I think I understand what happens here. The question is the following: is there a rule of thumb when (in which methods) Cocos2D retains objects (in this case testsprite)?

Bye, Christian

itsame69
  • 1,452
  • 4
  • 17
  • 33
  • Don't worry about retain counts yourself. Retain an object when you get it, release it when you're done. If everybody did their jobs, there won't be a problem. – EmilioPelaez Jun 25 '12 at 16:52

2 Answers2

2
  1. If possible use the class functions because they are autoreleased.
  2. Adding a CCNode with addChild will retain the node. If you did some alloc init stuff, release it after adding it as a child
  3. Adding anything to an array retains the object. You can safely release an object if you added it to an array.

autoreleased:

CCSprite *sprite = [CCSprite spriteWithFile:@"icon.png"];

manual memory management

CCSprite *sprite = [[CCSprite alloc] initWithFile:@"icon.png"];

Dont let the retainCount confuse you. Each line of code will maybe retain the object. If it is done well, the underlying code will release it automatically after it is finished.

A common example when you have to type release.

NSMutableArray *units = [NSMutableArray array];
for (int i = 0; i < 42; i++)
{
    CCNode *unit = [[MyUnit alloc] init]; // retain +1
    [units addObject:unit]; // retain +1
    [unit release]; // retain -1
}
vikingosegundo
  • 51,126
  • 14
  • 131
  • 172
zeiteisen
  • 6,877
  • 5
  • 44
  • 68
  • Thanks for the reply. One more question: if - in your last code snippet - I would call [units release] later on, this would release the array plus all objects (CCNodes) assigned to that array? – itsame69 Jun 25 '12 at 11:38
  • yes, if you release the array it releases its full content. All MyUnits gets dealloced after the [units release]; – zeiteisen Jun 25 '12 at 14:04
1

The rule is the same as for any other Cocoa code: retain something when you need it to stick around. Release it when you're done with it.

Also, the retainCount method is generally useless.

Community
  • 1
  • 1
jscs
  • 62,161
  • 12
  • 145
  • 186