0

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!

Community
  • 1
  • 1
hzxu
  • 5,753
  • 11
  • 60
  • 95

1 Answers1

10

Sending release to an NSTimer won't invalidate it.

If the NSTimer is 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 invalidate to a scheduled timer, the run loop releases the timer.

If the NSTimer is not scheduled in a run loop, then it doesn't need to be invalidated. But it's safe to send invalidate to a timer whether it's scheduled, not scheduled, or already invalidated.

So you should send your timer invalidate in your dealloc method, 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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • so is it true that invalidate will also release it? – hzxu Aug 07 '12 at 06:56
  • 2
    Whether `invalidate` releases the timer is irrelevant. That's a private implementation detail. *You* need to release it *if* you own a reference to it. Read *[Cocoa Core Competencies: Memory management](http://developer.apple.com/library/ios/#DOCUMENTATION/General/Conceptual/DevPedia-CocoaCore/MemoryManagement.html)*. – rob mayoff Aug 07 '12 at 07:00
  • Excellent answer, this really tripped me up back when I was a beginner +1. – borrrden Aug 07 '12 at 07:10