1

I am creating a new UIViewController with the below code

GameViewController *temp = [[GameViewController alloc] initWithNibName:@"GameViewController" bundle:nil];
NSLog(@"retain count%d", [temp retainCount]);
temp.backgroundMusic = backgroundMusic;
self.gameView = temp;
[temp release];     
[self presentModalViewController:gameView animated:YES];                
[gameView release];

but when I look at retain counts, my temp view controller returns 4.

How this is possible?? Because it is 4, when I dismiss the view controller I cant remove it from memory and my game is going on playing. (I can see the effects of AI playing).

  • [gameView release] should be self.gameView=nil; (depending if you have declared the gameView property with retain) – AndersK Sep 20 '11 at 09:55

4 Answers4

6

Never use retainCount, it does not work the way you think it does.

If you need to see where retains, releases and autoreleases occur for an object use instruments:

Run in instruments, in Allocations set "Record reference counts" on on (you have to stop recording to set the option). Cause the picker to run, stop recording, search for there ivar (datePickerView), drill down and you will be able to see where all retains, releases and autoreleases occurred.

Example screenshot

zaph
  • 111,848
  • 21
  • 189
  • 228
  • 1
    Finally, someone with a demonstration of using the Allocations instrument to track retain counts! Thank you! – bbum Sep 20 '11 at 14:49
4

"You should never use retainCount". Here is a very good description, why to not: stackoverflow

Community
  • 1
  • 1
Infinite Possibilities
  • 7,415
  • 13
  • 55
  • 118
1

I advise you never using retainCount because it usually gives false information about the actual retaincount of your object!!!!

Just follow the appropiate memory management practices!!!! It's very simple really, just follow the NARC principle, release only the objects that have these words: New Alloc Retain Copy. NARC! :)

I strongly advise you using the memory leaks tool from instruments that tells you which objects were not released and which objects where released and you are trying to access.

Jose Luis
  • 3,307
  • 3
  • 36
  • 53
1

In GameViewController have you released your background music as

- (void)viewDidLoad{
   //Other nils
   self.backgroundMusic = nil;
}
- (void)dealloc{
    //Other releases
    [backgroundMusic release];
    [super dealloc];
}
Saran
  • 6,274
  • 3
  • 39
  • 48