NSTimer 选择器调用
有人可以向我解释一下 NSTimer 的行为到底是怎样的吗?
基本上我想知道是否有办法让 NSTimer 事件始终发生。当前正在执行某些操作时发生的事件。
例如,in:
NSTimer* testTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(testMethod) userInfo:nil repeats: NO];
for (int i=0; i<9999; i++) {
NSLog(@"%i", i);
}
testMethod 永远不会被执行,因为事件触发时正在执行 for 循环。
Can someone explain to me how exactly the NSTimer behavior is?
Basically I want to know if there is a way to always have the NSTimer event happen. Event if there is currently something executing.
For example, in:
NSTimer* testTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(testMethod) userInfo:nil repeats: NO];
for (int i=0; i<9999; i++) {
NSLog(@"%i", i);
}
testMethod will never be executed since the for loop is being executed when the event fires.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当计时器触发时,它的选择器被添加到运行循环中以尽快执行。
但是,您正在创建一个循环,因此运行循环永远不会进行更改来执行计时器的选择器,从而导致您所看到的结果 - 应用程序在运行计时器的选择器之前等待循环完成。
如果您有一个长时间运行的任务,最好将其放入一个新线程中 - 尝试查看 performSelectorInBackground 并阅读 Objective-C 中的线程。
When the timer fires, it's selector is added to the run loop to be executed as soon as possible.
However, you're creating a loop so the run loop never gets a change to do the timer's selector resulting in what you're seeing - the app waits for the loop to finish before running your timer's selector.
If you have a long running task, it's best to put it into a new thread - try looking at performSelectorInBackground and reading up on threading in objective-c.