Seasoned Cocoa developers may snicker at the title of this post, because it's probably obvious to them. It should have been obvious to me, but it wasn't. Maybe I can save someone some head-scratching by relaying my tale.
NSTimers retain their target. Now, I've been around the Cocoa block a few times, so I knew this to be the case (the docs state it explicitly), but I clearly hadn't thought through the ramifications. Walk with me for a minute.
Let's say you have a window, MainWindow, and a controller class for it, MainWindowController. You put a timer on it to periodically do some stuff. It might look like this:
@interface MainWindowController : NSWindowController
{
NSTimer* myTimer;
}
- (void) doSomeStuff;
@end
@implementation MainWindowController
- (id) initWithWindow:(NSWindow*)window
{
self = [super initWithWindow:window];
if( self ) {
const NSTimeInterval timerInterval = 10.0f;
myTimer = [NSTimer scheduledTimerWithTimeInterval:timerInterval
target:self
selector:@selector(doSomeStuff)
userInfo:nil
repeats:YES];
}
return self;
}
- (void) dealloc
{
[myTimer invalidate], myTimer = nil;
[super dealloc];
}
- (void) doSomeStuff
{
NSLog( @"doing stuff" );
}
@end
Seems reasonable, no? It did to me. The problem is that, as the docs state, NSTimers retain their target. When you create that timer in initWithWindow:, it retains the window controller, which means dealloc will never be called. dealloc isn't called until the controller's retain count is zero, and until the timer invalidates (which will be never, on a repeating timer), the controller's retain count will never be zero.
The solution would be to invalidate the timer elsewhere, perhaps in windowWillClose: (of course, your controller must also be the window's delegate for that to happen).
- (void) windowWillClose:(NSNotification*)notification
{
[myTimer invalidate], myTimer = nil;
}
Another thing I'd like to mention is the use of retainCount for debugging purposes. I've found that brand new Cocoa programmers tend to rely way too much on retainCount to try to figure out their memory management issues. Cocoa pros, on the other hand, will tell you to never ever call retainCount. You can't get any useful information from it, some say, because you can't know who's retaining your objects.
I think the truth lies somewhere in between. The truth is, you should know who's retaining your objects, and why. Though retainCount shouldn't be the first thing you look to, it can be useful on occasion if it seems like things aren't working as you expect.
In my case, I observed that calling initWithWindowNibName: on my window controller was returning an object with a retainCount of 2, when I was expecting 1. From there it was a pretty short walk to get to "ok, my timer is created here, but it's invalidated in dealloc… oh, wait."
No comments:
Post a Comment