itsame69
itsame69

Reputation: 1560

When does Cocos2d retain objects?

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

Upvotes: 1

Views: 715

Answers (2)

zeiteisen
zeiteisen

Reputation: 7168

  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
}

Upvotes: 2

jscs
jscs

Reputation: 64002

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.

Upvotes: 1

Related Questions