为什么这个调度不起作用?

时间:2015-11-19 21:51:29

标签: swift grand-central-dispatch

我试图用GCD计时器来解决问题。除了viewDidLoad:

之外,应用程序没有任何内容
let crow2 = Crow()
        crow2.spawn(world, position: CGPoint(x: 220, y: 210))

我期待" tick"每2秒在调试面板中打印但没有任何反应。这是完整的输出:

    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")
        } 
}

有人可以说为什么它没有滴答声?

1 个答案:

答案 0 :(得分:0)

我认为没有任何事情发生,因为'timerSource'在viewDidLoad的末尾被取消分配。当我把它变成全局时它按预期工作。由于timerSource的声明是指q,q也必须是全局的。

另一个问题是,由于发送时间是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")
    }
}