I have a problem with an Objective-C object (in an iOS game application) that is mysteriously freed up.
The object is an instance of GameCharacter, which is created in this way:
for (int c = 0; c < kNrOfGuards; c++) { GameCharacter* guard = [[GameCharacter alloc] initGuard:self sprite:guardSprite]; [characterArray addObject:guard]; [guard release]; }
I also have a convenient method for searching for GameCharacter:
- (GameCharacter*)findCharacterWithIndex:(int)index { return [characterArray objectAtIndex:index]; }
And the code generating the error looks like this:
for (int c = 0; c < [self characterCount]; c++) { GameCharacter* tempCharacter = [self findCharacterWithIndex:c]; if (tempCharacter.playerId == playerIndex]) { ... } }
Running this code for some time (never right away) generates an error in the console:
[GameCharacter playerId]: message sent to freed instance 0x4e47560
Using the NSZombieEnabled trick, I managed to find the object (s) that was causing the problem, but I still can not understand why this object is being freed. Finding my code for "release" / "dealloc" gives no hints.
I tried to remove the “release” (and even add “save”!) To the alloc / init loop (see above), it seems to extend the application’s runtime, but will not completely fix the problem.
Any hints would be much appreciated!
EDIT
Thanks to quixoto, Olie, Eiko, tc., I found out that this is my GameCharacter object that is being released, but I still don't understand 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 “Finish”, the selected character on the screen changes and, therefore, the selectedCharacter property on the TiledGroundLayer (step No. 2-4). Since the selectedCharacter belongs to the previous GameCharacter object, it seems to be freed. But why is it not saved properly with NSMutableArray ( [characterArray addObject:guard]; )?