NSTimer 冻结应用程序直到它再次被触发?

发布于 2024-08-28 20:13:17 字数 642 浏览 1 评论 0原文

我有一个简单的应用程序,带有按钮、UIImageView 和 NSTimer。 计时器每 5 秒重复启动一次,以使用新图像更新 ImageView,而按钮只是停止计时器并切换到另一个视图。

问题是,当我按下按钮时,几秒钟内没有任何反应(直到计时器再次启动)。

有没有办法让按钮停止计时器并在任何给定时间而不是在计时器间隔之间执行其工作?

该按钮在 InterfaceBuilder 中定义并连接到代码中的函数。

NSTimer 代码:(我尝试过使用 & ,但没有将其添加到 RunLoop 中)。

<代码> updateTimer = [NSTimerchedTimerWithTimeInterval:5 目标:self 选择器:@selector(updateImageViews) userInfo:nil 重复:YES];

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[[NSRunLoop currentRunLoop] addTimer:updateTimer forMode:NSDefaultRunLoopMode];
[runLoop run];

谢谢!

I have a simple app with a button, UIImageView and a NSTimer.
The timer is fired up every 5 seconds repeatedly to update the ImageView with a new image, while the button simply stops the timer and switches to another View.

The problem is that when I press the button, nothing happens for a few seconds (until the timer fires up again).

Is there a way to cause the button to stop the timer and do its job at any given time instead of between intervals of the timer?

The button is defined in the InterfaceBuilder and connected to a function in the code.

The NSTimer code: (I've tried with & without adding it to the RunLoop).


updateTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(updateImageViews) userInfo:nil repeats:YES];

NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[[NSRunLoop currentRunLoop] addTimer:updateTimer forMode:NSDefaultRunLoopMode];
[runLoop run];

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

牛↙奶布丁 2024-09-04 20:13:17

“请注意,从 NSRunloop 的角度来看,NSTimer 对象不是“输入”——它们是一种特殊类型,这意味着它们在触发时不会导致运行循环返回。” (来自 NSRunLoop 类参考)-所以我认为你阻止了运行循环继续?也许将计时器放到不同的线程作为解决方案?
我自己也有这个问题:(

"Note that from the perspective of NSRunloop, NSTimer objects are not "input"—they are a special type, and one of the things that means is that they do not cause the run loop to return when they fire." (from NSRunLoop Class Reference) - so I think you block the runloop from continuing? Perhaps put the timer to a different thread as solution?
I have problems on this on my own, too :(

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