为什么此调度不起作用?

罗伯特·L

我正在尝试使用带有GCD的计时器。除了viewDidLoad外,该应用程序什么都没有:

    import UIKit

    class ViewController: UIViewController {
        override func viewDidLoad() {
            super.viewDidLoad()

            let delay = 2
            let q = dispatch_queue_create("dispatchQ", DISPATCH_QUEUE_SERIAL)
            let timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q)
            print("timerSource created")

            dispatch_source_set_timer(timerSource, DISPATCH_TIME_NOW,
                UInt64(delay) * UInt64(NSEC_PER_SEC),
                UInt64(0.5 * Double(NSEC_PER_SEC)))
            print("timerSource time set")

            dispatch_source_set_event_handler(timerSource, { print("tick") })
            print("timerSource event set")

            dispatch_resume(timerSource)
            print("timerSource resumed")
        } 
}

我希望每2秒在调试面板中打印一次“滴答”,但什么也没有发生。这是完整的输出:

timerSource created
timerSource time set
timerSource event set
timerSource resumed

有人可以说为什么它没有打勾吗?

罗伯特·L

我认为什么都没有发生,因为'timerSource'在viewDidLoad的末尾被取消分配。当我使其成为全球性产品时,它会按预期运行。而且由于timerSource的声明引用了q,所以q也必须是全局的。

另一个t周是,由于调度时间为DISPATCH_TIME_NOW,因此第一次滴答即刻发生了,这是我所不希望的,因此我不得不缩短第一次时间(感谢Matt)。

因此,有效的ViewController如下所示:

import UIKit

let q = dispatch_queue_create("dispatchQ", DISPATCH_QUEUE_SERIAL)
let timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, q)

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        let delay = 3
        var firstTime = true

        dispatch_source_set_timer(timerSource, DISPATCH_TIME_NOW,
            UInt64(delay) * UInt64(NSEC_PER_SEC),
            UInt64(0.5 * Double(NSEC_PER_SEC)))
        print("timerSource time set")

        dispatch_source_set_event_handler(timerSource)
            {
                if firstTime {
                    firstTime = false
                    return
                }
                print("tick")
            }
        print("timerSource event set")

        dispatch_resume(timerSource)
        print("timerSource resumed")
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

为什么此NotificationListenerService不起作用

来自分类Dev

为什么此for循环不起作用?

来自分类Dev

为什么此查询不起作用?

来自分类Dev

为什么此XQuery不起作用?

来自分类Dev

为什么此聚合不起作用?

来自分类Dev

为什么此动画不起作用?

来自分类Dev

为什么此代码不起作用?

来自分类Dev

为什么此cronjob不起作用?

来自分类Dev

为什么此toggleClass()不起作用?

来自分类Dev

为什么此查询不起作用

来自分类Dev

为什么我的调度对按钮单击事件不起作用?

来自分类Dev

为什么此Django日志记录不起作用?

来自分类Dev

为什么此dplyr dput不起作用?

来自分类Dev

为什么此regexp-replace不起作用?

来自分类Dev

为什么此haskell类型签名不起作用?

来自分类Dev

为什么此Python JDBC连接不起作用?

来自分类Dev

为什么此dynamic_cast <T>不起作用?

来自分类Dev

为什么此翻译动画不起作用?

来自分类Dev

为什么此递归模板不起作用?

来自分类Dev

为什么此线段相交算法不起作用?

来自分类Dev

为什么此滚动动画不起作用?

来自分类Dev

为什么此Move构造函数不起作用

来自分类Dev

为什么此递归函数不起作用

来自分类Dev

为什么此linq投影不起作用?

来自分类Dev

为什么此javascript regex文字不起作用?

来自分类Dev

为什么此define指令似乎不起作用?

来自分类Dev

为什么此D3拖动不起作用?

来自分类Dev

为什么此Shell脚本不起作用?

来自分类Dev

为什么此GROUP BY查询不起作用?