Would NSTImer events block the main thread?

匆匆过客 提交于 2019-11-30 21:39:35
visakh7

From the documents

Timers work in conjunction with run loops. To use a timer effectively, you should be aware of how run loops operate—see NSRunLoop and Threading Programming Guide.

Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A non-repeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method. Calling this method requests the removal of the timer from the current run loop; as a result, you should always call the invalidate method from the same thread on which the timer was installed. Invalidating the timer immediately disables it so that it no longer affects the run loop. The run loop then removes and releases the timer, either just before the invalidate method returns or at some later point. Once invalidated, timer objects cannot be reused.

I believe NSTimer does not block the UI thread. Also take a look at this previous SO question NSTimer and updating UI

That depends. Most of the time, this won't be a problem.

If, however, both of the following criteria are met, an NSTimer will block the UI thread:

  1. The timer is scheduled on the NSRunLoop of the main thread. This will be the case whenever you created it by calling one of NStimer's scheduledTimerWith... class-methods on the main thread.
  2. The method, which is called when the timer fires, performs "lengthy" tasks. Things like synchronously performed fetches/url-requests come to mind...
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!