Member-only story

Swift Timer with retain cycle?

The Blue Prototype
3 min readJun 13, 2020

--

According to Apple — A timer that fires after a certain time interval has elapsed, sending a specified message to a target object.

Timers work in conjunction with run loops. Run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.

Types of Timer

  • Repeating Timer
  • Non-repeating Timer

Non-repeating Timer

A non-repeating timer fires once and then invalidates itself automatically, thereby preventing the timer from firing again.

In this scenario, we don't need to call invalidate() manually to cancel a timer. It removes own reference automatically.

Repeating Timer

A repeating timer fires and then reschedules itself on the same run loop. A repeating timer always schedules itself based on the scheduled firing time, as opposed to the actual firing time.

For example, if a timer is scheduled to fire at a particular time and every 5 seconds after that, the scheduled firing time will always fall on the original 5-second time intervals, even if the actual firing time gets delayed. If the firing time is delayed so far that it passes one or more of the scheduled firing times, the timer is fired only once for that time period; the timer is then rescheduled, after firing, for the next scheduled firing time in the…

--

--

Responses (2)