定时器不重复(Grand Central Dispatch)

时间:2015-01-27 15:56:08

标签: ios xcode swift grand-central-dispatch nstimer

我正在尝试学习如何在后台线程上调度计算,然后更新UI。当我在使用谷歌地图的现有项目中尝试此操作时,“背景”后跟“主”打印一次。不再进行打印,就好像计时器不重复一样。

此外,当我创建一个空白的应用程序并添加此代码时,根本没有任何打印。

let queue = dispatch_queue_create("myTimer", nil);
let timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);

dispatch_source_set_event_handler(timer) {
    println("background")
    dispatch_async(dispatch_get_main_queue(), { println("main") })
}

dispatch_resume(timer)

1 个答案:

答案 0 :(得分:8)

确保长寿的内容引用此队列和此计时器。如果没有明确检查,我在此片段中的展示就是timerqueue将在超出范围时发布。 dispatch_resume可能导致第一个事件排队,这可能导致queuetimer活得足够长以执行第一次迭代,之后他们的保留计数变为零并且他们得到解除分配。

尝试确保它们坚持一段时间......

例如,从Xcode中的iOS Single View Application项目模板开始,以及AppDelegate.swift中的以下内容,计时器重复正常:

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var queue: dispatch_queue_t?
    var timer: dispatch_source_t?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        queue = dispatch_queue_create("myTimer", nil);
        timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC);

        dispatch_source_set_event_handler(timer) {
            println("background")
            dispatch_async(dispatch_get_main_queue(), { println("main") })
        }

        dispatch_resume(timer)

        return true
    }
}