NSTimer retain problem

Discussion in 'iOS Programming' started by xcodeNewbie, Apr 16, 2012.

  1. xcodeNewbie macrumors member

    Joined:
    Jul 1, 2011
    #1
    Hello, I've been having trouble with my memory management concerning some timers. I have a class called "Planet" that uses two timers as instance variables. The planet objects I create aren't being deallocated when they should as their retain count is too high. Below is a line of code from my initialization method of Planet:
    Code:
     NSLog(@"%i", [self retainCount]);
            self.battleTimer = [NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(battle) userInfo:nil repeats:YES];
    self.makeShipTimer = [NSTimer scheduledTimerWithTimeInterval:(60-radius)/15 target:self selector:@selector(makeShip) userInfo:nil repeats:YES];
    This comes right at the beginning of my initialization method. As I would expect, the NSLOG prints out 1. However, If I add the NSLOG after the timers are created:
    Code:
    self.battleTimer = [NSTimer scheduledTimerWithTimeInterval:0.3f target:self selector:@selector(battle) userInfo:nil repeats:YES];
            self.makeShipTimer = [NSTimer scheduledTimerWithTimeInterval:(60-radius)/15 target:self selector:@selector(makeShip) userInfo:nil repeats:YES]; 
    NSLog(@"%i", [self retainCount]);
    The NSLOG prints 3!?!?! For some reason the timers are retaining the planet object that creates them. I'm not sure if this is normal behavior or not but it's making it so that the planets don't get deallocated when I'm through with them. Its giving me major memory leaks. Can somebody please help?
     
  2. ArtOfWarfare macrumors 604

    ArtOfWarfare

    Joined:
    Nov 26, 2007
    #2
    I'm not very good with memory management, and thus I consider ARC a godsend, however my understanding is:

    1 - never look at what "retainCount" returns.
    2 - don't worry about what other methods have. Each "alloc" or "retain" should have a matching "release" or "autorelease" occurring just as often (ie, if the retain occurs in a loop, the matching release should be in the same loop.)

    Don't worry about it if the timer is retaining your object. It'll release your object when it's ready to (probably after it's done firing?) I don't know. One, I'm on an iPhone and haven't checked the NSTimer docs, and two, as I said, I'm poor at memory management, but I think I'm right here.
     

Share This Page