DispatchSourceTimer和Swift 3.0

编程入门 行业动态 更新时间:2024-10-21 16:09:09
本文介绍了DispatchSourceTimer和Swift 3.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我不知道如何在Swift 3.0中使调度计时器重复工作.我的代码:

I can't figure out how to make dispatch timer work repeatedly in Swift 3.0. My code:

let queue = DispatchQueue(label: "com.firm.app.timer", attributes: DispatchQueue.Attributes.concurrent) let timer = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags(rawValue: UInt(0)), queue: queue) timer.scheduleRepeating(deadline: DispatchTime.now(), interval: .seconds(5), leeway: .seconds(1) ) timer.setEventHandler(handler: { //a bunch of code here }) timer.resume()

计时器仅触发一次,不会像应有的那样重复自身.我该如何解决?

Timer just fires one time and doesn't repeat itself like it should be. How can I fix this?

推荐答案

确保计时器不会超出范围.与Timer不同(在其上安排RunLoop会保留强引用,直到Timer无效),您需要维护自己对GCD计时器的强引用,例如:

Make sure the timer doesn't fall out of scope. Unlike Timer (where the RunLoop on which you schedule it keeps the strong reference until the Timer is invalidated), you need to maintain your own strong reference to your GCD timers, e.g.:

var timer: DispatchSourceTimer? private func startTimer() { let queue = DispatchQueue(label: "com.firm.app.timer", attributes: .concurrent) timer?.cancel() // cancel previous timer if any timer = DispatchSource.makeTimerSource(queue: queue) timer?.schedule(deadline: .now(), repeating: .seconds(5), leeway: .milliseconds(100)) // or, in Swift 3: // // timer?.scheduleRepeating(deadline: .now(), interval: .seconds(5), leeway: .seconds(1)) timer?.setEventHandler { [weak self] in // `[weak self]` only needed if you reference `self` in this closure and you want to prevent strong reference cycle print(Date()) } timer?.resume() } private func stopTimer() { timer?.cancel() timer = nil }

更多推荐

DispatchSourceTimer和Swift 3.0

本文发布于:2023-11-26 17:08:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634468.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:DispatchSourceTimer   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!