Search code examples
iosobjective-cnstimer

Using invalidate in NSTimer in iOS?


Suppose if i create an NSTimer with the code. The code calls a function which dismisses view controller after 90 second

  • A) Is it necessary to InValidate NSTimer every time when that view controller dismisses?
  • B) What is the use of invalidate? And when to use invalidate ?
  • C) If i don't use invalidate will it cause any side effects like Memory Leak? (edited)

Please explain.


Solution

  • If you haven't already, I would encourage you to review the documentation for NSTimer, as two of your three questions are answered clearly there (emphasis below mine):


    A) Is it necessary to InValidate NSTimer every time when that view controller dismisses?

    Comparing Repeating and Nonrepeating Timers

    You specify whether a timer is repeating or nonrepeating at creation time. A nonrepeating timer fires once and then invalidates itself automatically, thereby preventing the timer from firing again. By contrast, a repeating timer fires and then reschedules itself on the same run loop [...]


    B) What is the use of invalidate? And when to use invalidate ?

    Stopping a Timer

    • invalidate

      Stops the timer from ever firing again and requests its removal from its run loop.


    C) If i don't use invalidate will it cause any side effects like Memory Leak? (edited)

    The documentation linked above does not explicity speak to this particular aspect of using NSTimer, but a simple search yielded a particularly helpful Stack Overflow question regarding NSTimer-related memory management. I've included the most relevant content from the accepted answer below:

    Yes, NSTimer will maintain a strong reference to the target, which can cause (especially in repeating timers) strong reference cycles (a.k.a. retain cycles). In your example, though, the timer does not repeat, and is delayed only 0.5, so worst case scenario, you will have a strong reference cycle that will automatically resolve itself in 0.5 seconds.

    But a common example of an unresolved strong reference cycle would be to have a UIViewController with a NSTimer property that repeats, but because the NSTimer has a strong reference to the UIViewController, the controller will end up being retained.

    So, if you're keeping the NSTimer as an instance variable, then, yes, you should invalidate it, to resolve the strong reference cycle. If you're just calling the scheduledTimerWithTimeInterval, but not saving it to an instance variable (as one might infer from your example), then your strong reference cycle will be resolved when the NSTimer is complete.