从辅助线程启动NSTimer时出现问题 [英] Problems launching an NSTimer from a secondary thread

查看:61
本文介绍了从辅助线程启动NSTimer时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中注意到,当我尝试从辅助线程启动NSTimer时,它不起作用.我尝试调用+ [NSRunLoop currentRunLoop],以防万一问题是线程没有运行循环...但没有骰子. (请注意,这是在黑暗中拍摄的.文档说这会创建一个运行循环,但是也许我需要做其他配置,而实际上并不需要.)

I'm noticing in my code that when I try to start an NSTimer from a secondary thread, it doesn't work. I tried calling +[NSRunLoop currentRunLoop] just in case the problem was that the thread didn't have a run loop...but no dice. (Note that that was a shot in the dark. The docs said that would create a run loop, but perhaps there's other configuration that I needed to do, and didn't.)

我知道像-[NSObject performSelectorOnMainThread:]这样的调用可以解决我的问题(实际上,我的解决方案是将代码简单地移动到主线程中,效果很好),但是我仍然对此感到好奇为什么会出现此问题.从辅助线程启动NSTimer实际上是不可能的吗?有解决方法吗?

I'm aware of calls like -[NSObject performSelectorOnMainThread:] which could solve my problem (in fact, my solution was to simply move this code into the primary thread, which works fine), but I'm still curious about why this problem occurred. Is it in fact impossible to start an NSTimer from a secondary thread? Is there a workaround?

非常感谢.

推荐答案

请确保您A)将计时器添加到当前运行循环中,并且B)运行所述运行循环.计时器触发时,如果您想退出[runloop run]调用,请调用[runloop stop].

Make sure you A) add the timer to the current runloop, and B) run said runloop. When your timer fires, if you'd like to exit the [runloop run] invocation, call [runloop stop].

这篇关于从辅助线程启动NSTimer时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆