I have a class which has an NSTimer, when I release it, does invalidate also called? Or can I do them both in dealloc:
- (void)dealloc
{
[_timer invalidate];
[_timer release];
[super dealloc];
}
I read in this thread:
invalidate method call also does a release
the picked answer says invalidate method also does a release, so I do not need to release it if I invalidate it?
Thanks!
Sending
releaseto anNSTimerwon’t invalidate it.If the
NSTimeris scheduled in a run loop, then the run loop retains the timer. So even when you release the (scheduled) timer, it still has a retain count larger than zero. Also, it will keep firing. If the timer’s target has been deallocated, the app will probably crash when the timer fires.When you send
invalidateto a scheduled timer, the run loop releases the timer.If the
NSTimeris not scheduled in a run loop, then it doesn’t need to be invalidated. But it’s safe to sendinvalidateto a timer whether it’s scheduled, not scheduled, or already invalidated.So you should send your timer
invalidatein yourdeallocmethod, unless you’re sure it’s already been invalidated.If you created the timer using
[[NSTimer alloc] initWith...], then you should also release it. But if you created the timer using[NSTimer timerWith...]or[NSTimer scheduledTimerWith...], you should not release it, because you don’t own a reference to it.