NSTimer 选择器调用

发布于 2024-09-13 15:34:44 字数 371 浏览 0 评论 0原文

有人可以向我解释一下 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素食主义者 2024-09-20 15:34:48

当计时器触发时,它的选择器被添加到运行循环中以尽快执行。

但是,您正在创建一个循环,因此运行循环永远不会进行更改来执行计时器的选择器,从而导致您所看到的结果 - 应用程序在运行计时器的选择器之前等待循环完成。

如果您有一个长时间运行的任务,最好将其放入一个新线程中 - 尝试查看 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文