views:

152

answers:

3

After I finished coding the difficult parts of my game, I found some memory management bugs.

objects is a NSMutableArray holding a custom class.

- (void) spawnObjects
{   
    for (int index = 0; index < INITIAL_OBJECTS; index++)
    {
     [objects addObject:[[[MatchObject alloc] initWithImageNameID:(index % 3)] autorelease]];
     [[objects objectAtIndex:index] setPosition:[GameLayer randomPoint]];
    }

    ...
}

I later use this function.

- (void) checkAllSprites
{

    NSMutableArray *spritesToDelete = [NSMutableArray array];
    for (int index = 0; index < [points count] - 1; index ++)
    {
     for (MatchObject *planetLike in objects)
     {
      CGPoint point1 = [[points objectAtIndex:index] CGPointValue];
      CGPoint point2 = [[points objectAtIndex:index+1] CGPointValue];
      if ([GameLayer lineIntersectsCircle:point1 :point2 :[planetLike position] :16.0f])
      {

       ParticleSystem *planetDeath = [ParticlePlanetDeath node];
       planetDeath.texture = [[TextureMgr sharedTextureMgr] addImage:@"fire.pvr"];
       planetDeath.position = [planetLike position];
       [self addChild:planetDeath z:0 tag:2];

       [spritesToDelete addObject:planetLike];

       [self removeChild:planetLike cleanup:YES];

      }

     }
    }
    [objects removeObjectsInArray:spritesToDelete];
    [spritesToDelete removeAllObjects];

}

If I do not autorelease in the first function, the app works fine. If I do, then I try to access a dealloced object ([MatchObject position]).

What's wrong?!

A: 

Any chance that you're doing something in the "removeChild" method that ends up releasing the object? There doen't appear to be anything wrong with the code that you posted...

Mark Bessey
removeChild decrements the retain count, addChild increments it. Would that be a problem?
how? show code. Also show code for creating objects array.
A: 

It sounds like you're referencing freed memory. When you actually release the memory, it crashes because your program referencs freed memory. When you don't release it using autorelease, it stil works because even though there's a memory leak the system doesn't notice it because since the object isn't actually freed so the reference to it doesn't cause a problem.

So, get out the magnifying glass and look over your code again, and start using the debugger ... have fun :)

Larry Watanabe
Thanks, found the problem in the chipmunk function.
the chipmunk function?
Philippe Leybaert
Chipmunk is a 2D physics library that's packaged with Cocos2d-iPhone, which the OP is using.
adurdin
+1  A: 

Just a wild guess:

I suppose addChild is retaining the object and removeChild is releasing the object.

But what happens when removeChild doesn't find the object (i.e. if it's not a child)? Does it release the object too in that case? (which it shouldn't do)

Philippe Leybaert