Why DispatchSource.makeTimerSource not working?
Say you did the following
and proceeded to your business, but the timer fired once or even not a single time. Why? It's because your timer
object has been eaten by garbage collector, and when DispatchSourceTimer
is deinited, it (obviously) stops itself. It's worth reminding that GC is triggered when scope closes, in our case — after async
block fired. Therefore, if you want to regularly run certain task, you should store reference to timer object in a global storage, which would live as long as you want, but not the GC. It's also recommended to wrap access to this storage with synchronous serial queue to avoid shameful race conditions.
By the way, there might be an opposite situation: timer wouldn't destroy when you destroy all references to it. The reason is timer handler might have a strong reference to some object or self
. In order to ensure it wouldn't happen, explicitly specify [weak self]
in timer handler header.
Pending comments