如何将 NSTimer 嵌套在另一个 NSTimer 中?
我想要一个 NSTimer 每 1 秒执行一次,并有另一个 NSTimer 在该计时器内执行略小于 1 秒。
实际上我不确定最好的方法是什么,但我希望每秒出现一个随机图像,然后在那一秒后消失。
所以我需要某种停顿或可以打发时间的东西,然后再次执行隐藏按钮。
如果我将按钮隐藏设置为TRUE,然后将其设置为FALSE,那么出现时间会很短,我如何才能停止或进行第二遍然后再次隐藏图像?
提前致谢
I would like to have an NSTimer which executes every 1 second and have another NSTimer which executes within that timer slightly less than 1 second.
Actually I am not sure what is the best way to do this, but I would like a random image to appear every second and then disappear after after that second.
So I need some kind of stall or something which can pass the time and then execute the hide button again.
If I set the buttons hidden to TRUE and then set it to FALSE, this appearance time will be so short, how can I stall or make the second pass and then hide the image again?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以尝试将自己设置为在指定时间间隔后显示和隐藏对象的恒定循环,直到使用
performSelector:withObject:afterDelay:
方法在两个相反的方法中相互起作用:您可以通过放置一个
if
语句来中断循环,该语句为您检查performSelector:withObject:afterDelay:
调用 。You can try setting yourself into a constant cycle of showing and hiding the object after a specified interval until you interrupt it by using the
performSelector:withObject:afterDelay:
method reciprocally in two counter-acting methods:You can interrupt the cycle by putting an
if
statement which checks some end condition for you around theperformSelector:withObject:afterDelay:
call .我建议使用 NSTimer 的
initWithFireDate:interval:target:selector:userInfo:repeats:
。这将使您可以定期触发计时器(如果将repeats
设置为YES
),并且您可以指定fireDate
(第一个定时器被触发的时间)到立即为一个循环,稍晚为另一个循环。与performSelector
相比,此方法的优点在于,可以通过向计时器发送invalidate
轻松终止它,并且不会因您可能在其中任何一个中拥有的任何阻塞代码而延迟你的方法。I would recommend using NSTimer's
initWithFireDate:interval:target:selector:userInfo:repeats:
. This will let you have the timer fire at a regular interval (if you setrepeats
toYES
) and you can specify afireDate
(the first time the timer is fired) to immediately for one loop and slightly later for the other. What's better about this method compared toperformSelector
is that it can be easily terminated by sendinginvalidate
to the timers and will not be delayed by any blocking code you might have in either of your methods.