I have a problem with an Objective-C object (in an iOS game app) that is being mysteriously deallocated.
The object is a GameCharacter instance which is instantiated like so:
for (int c = 0; c < kNrOfGuards; c++) {
GameCharacter* guard = [[GameCharacter alloc] initGuard:self sprite:guardSprite];
[characterArray addObject:guard];
[guard release];
}
I also have a convenience method for finding a GameCharacter:
- (GameCharacter*)findCharacterWithIndex:(int)index {
return [characterArray objectAtIndex:index];
}
And the code that generates the error looks like:
for (int c = 0; c < [self characterCount]; c++) {
GameCharacter* tempCharacter = [self findCharacterWithIndex:c];
if (tempCharacter.playerId == playerIndex]) {
...
}
}
Running this code for some time (never immediately) generates an error in the Console:
[GameCharacter playerId]: message sent to deallocated instance 0x4e47560
With the NSZombieEnabled trick I've managed to track down the object(s) that is causing the problem, but I still can't understand why this object is being deallocated. Searching my code for "release"/"dealloc" does not produce any clues.
I've tried removing the "release" (and even adding a "retain"!) to the alloc/init loop (see top), it seems to extend the time the app can run but not remove the problem entirely.
Any hints would be much appreciated!
EDIT
Thanks to quixoto, Olie, Eiko, tc., I've figured out that it is my GameCharacter object that is being deallocated, but I still don't understand quite why. Here is the trace log in reverse chronological order:
#0 -[GameCharacter dealloc]
#1 objc_setProperty
#2 -[TiledGroundLayer setSelectedCharacter:]
#3 -[TiledGroundLayer selectNextCharacterForPlayer:searchStep:]
#4 -[GameScene selectNextCharacter:]
#5 -[GameScene endTurn]
#6 -[HUDLayer onClickDone:]
What happens here, is that the user clicks "Done", the selected character on screen is changed and thus the property selectedCharacter
on TiledGroundLayer (step #2-4). Since selectedCharacter
owns the previous GameCharacter object, it seems it is being deallocated. But why is it not being retained properly by the NSMutableArray ([characterArray addObject:guard];
)?