Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

xcodeNewbie

macrumors member
Original poster
Jul 1, 2011
65
0
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?
 

ArtOfWarfare

macrumors G3
Nov 26, 2007
9,567
6,073
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.