在循环中使用dispatch_after delay [英] Use dispatch_after delay inside a loop

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

问题描述

有什么方法在循环中使用 dispatch_after 吗?我有以下延迟函数:

Is there any way to use dispatch_after within a loop? I have the delay function below:

func delay(delay:Double, closure:()->()) {
    dispatch_after(
        dispatch_time(
            DISPATCH_TIME_NOW,
            Int64(delay * Double(NSEC_PER_SEC))
        ),
        dispatch_get_main_queue(), closure)
}

我想在这样的循环中执行它:

I want to execute it inside of a loop like this:

while true {
    self.delay(1.0) {
        // Do something repeatedly
    }
}

但我似乎无法使它工作。是否可以这样做?

But I can't seem to get it working. Is it possible to do this?

推荐答案

for (;;sleep(1)) {
    print("Hello Again");
}

*注意,这将锁定你的主线程每)1秒钟。如果这是一个问题,请在单独的线程中运行 while for循环,改为休眠NSThread,并在for循环中简单地 dispatch_get_main_queue()

*Note, this will lock your main thread every (1 second + 1 cycle) for 1 second. If this is an issue please run your whilefor loop in a separate thread, sleep that NSThread instead, and simply dispatch_get_main_queue() inside the for loop.

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

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