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?!
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 🙂