且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在后台线程上创建 NSTimer?

更新时间:2023-02-09 18:50:19

定时器需要安装到运行在已经运行的后台线程上的运行循环中.该线程必须继续运行运行循环才能真正触发计时器.为了让后台线程继续能够触发其他计时器事件,它需要产生一个新线程来实际处理事件(当然,假设您正在执行的处理需要大量时间).

The timer would need to be installed into a run loop operating on an already-running background thread. That thread would have to continue to run the run loop to have the timer actually fire. And for that background thread to continue being able to fire other timer events, it would need to spawn a new thread to actually handle events anyway (assuming, of course, that the processing you're doing takes a significant amount of time).

无论如何,我认为通过使用 Grand Central Dispatch 或 NSBlockOperation 生成新线程来处理计时器事件是对主线程的完全合理的使用.

For whatever it's worth, I think handling timer events by spawning a new thread using Grand Central Dispatch or NSBlockOperation is a perfectly reasonable use of your main thread.