我正在尝试使用带有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
有人可以说为什么它没有打勾吗?
我认为什么都没有发生,因为'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] 删除。
我来说两句