开发者

Would NSTImer events block the main thread?

开发者 https://www.devze.com 2023-03-04 22:49 出处:网络
When we use a NSTimer, once th开发者_JS百科e call back is called after the mentioned interval, does the UI would be blocked?That depends. Most of the time, this won\'t be a problem.

When we use a NSTimer, once th开发者_JS百科e call back is called after the mentioned interval, does the UI would be blocked?


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...


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

0

精彩评论

暂无评论...
验证码 换一张
取 消