dispatch_after循环/重复 [英] dispatch_after looped / repeated

查看:447
本文介绍了dispatch_after循环/重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个像这样的循环:

I am trying to create a loop like this:

while (TRUE){
  dispatch_after(...{
    <some action>
  });
}

在viewDidLoad之后.这个想法是重复重复dispatch_after. dispatch_after等待两秒钟,然后再执行操作.

After a viewDidLoad. The idea is to repeat the dispatch_after repeatedly. The dispatch_after waits two seconds before doing the action.

这不起作用-屏幕只是空白?是卡在循环中还是...?

This does not work - the screen just blanks? Is it stuck in looping or ...?

推荐答案

无论计划何时运行dispatch_after(...)调用,它都会立即返回.这意味着您的循环在分派它们之间不会等待两秒钟.相反,您正在建立一个无限的事物队列,该事物将从现在开始两秒钟发生,彼此之间不会两秒钟.

The dispatch_after(...) call returns immediately no matter when it is scheduled to run. This means that your loop is not waiting two seconds between dispatching them. Instead you are building an infinite queue of things that will happen two seconds from now, not two seconds between each other.

所以是的,您陷入了添加越来越多要执行的块的无限循环中.如果您希望每两秒钟发生某件事,那么您可以使用重复的NSTimer或在其内部包含块dispatch_after(这样,第二个块将在第一个块之后运行两秒钟).

So yes, you are stuck in an infinite loop of adding more and more blocks to be executed. If you want something to happen every two second then you could use a repeating NSTimer or have the block dispatch_after inside itself (so that the second block runs two seconds after the first).

这篇关于dispatch_after循环/重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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