ios奇门杂招iOS技术中心Swift3.0

Swift3.0 Timer

2016-09-22  本文已影响5080人  xiAo__Ju

Swift2.2到Swift3.0不知道几家欢喜几家愁,对于项目是纯Swift的我,反正是想艹阿婆他娘的。

2016年9月18号更新到了Xcode8,第二天将项目迁移到2.3。咦。。。好像没有改多少东西嘛!发了一个版本后,老大继续迁移到Swift3.0,我艹,什么玩意,999+个红。搞啊搞啊搞。。。

好了,废话不多说了,重点:

swift 2.3 Timer
private var timer = dispatch_source_t?()

func setTheTimer() {
        timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue())
        let start = dispatch_time(DISPATCH_TIME_NOW, Int64(pageStepTime * NSEC_PER_SEC))
        let interval = pageStepTime * NSEC_PER_SEC
        dispatch_source_set_timer(timer!, start, interval, 0)
        dispatch_source_set_event_handler(timer!) {
            self.yourMethod()
        }
        // 启动定时器
        dispatch_resume(timer!)
    }

private func deinitTimer() {
        if let time = self.timer {
            dispatch_source_cancel(time)
            timer = nil
        }
    }

迁移器自动转换的版本就不贴出来了,浪费您宝贵的时间。

swift 3.0 Timer
private var timer: DispatchSourceTimer?
var pageStepTime: DispatchTimeInterval = .seconds(5)

// deadline 结束时间
// interval 时间间隔
// leeway  时间精度
func setTheTimer() {
        timer = DispatchSource.makeTimerSource(queue: .main)
        timer?.scheduleRepeating(deadline: .now() + pageStepTime, interval: pageStepTime)
        timer?.setEventHandler {
            self.yourMethod()
        }
        // 启动定时器
        timer?.resume()
    }

func deinitTimer() {
        if let time = self.timer {
            time.cancel()
            timer = nil
        }
    }

反正各种谷歌,各种百度,就找到这一个
TimerTest_Swift3

SwiftTimer 手机尾号为1193的朋友给的,非常感谢
Each 定时器

最后附上自己[swift2.3] []版本和[swift3.0] []版本多线程的学习代码
[swift2.3]: https://github.com/huangboju/Moots/tree/master/Thread
[swift3.0]: https://github.com/huangboju/Moots/tree/master/Thread

上一篇 下一篇

猜你喜欢

热点阅读