I create a timer in my ViewDidLoad method of my view-controller.
NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(gameLoop:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(gameLoop:)];
NSTimer *t = [NSTimer timerWithTimeInterval: 1./30.
invocation:inv
repeats:YES];
NSRunLoop *runner = [NSRunLoop currentRunLoop];
[runner addTimer: t forMode: NSDefaultRunLoopMode];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(statTapped:)
name:@"statTapped"
object:nil];
Who and where can I deallocate this? If i try and do this from my dealloc it wont compile. Since t is not global.
-(void) dealloc
{
if (t)
{
[t invalidate];
[t release];
t=Nil;
}
}
Thanks,
Code
The simplest way is to just store it in your instance with a property:
viewDidLoad:
You should invalidate the timer when you don’t need it anymore. (Unless it has to keep running until you quit the application anyway. In that case there’s no point in invalidating it.)
It’s a bad idea to do that in -dealloc because:
Apple might add garbage collection to cocoa touch at some later point. If that happens, dealloc won’t get called anymore. That’s part of the reason why you shouldn’t do anything besides releasing objects in dealloc.
You’re UIViewController might be retained somewhere else, in which case dealloc won’t be called where expected as well. This might not be the case at the moment, but when you add additional functionality to your application suddendly you might need this functionality.
A good place to invalidate your timer might be in an action of the button called “pause” or similar.
Releasing the timer can still be done in -dealloc. Invalidated timers don’t retain their targets anymore.