加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

计时器不在Swift 3.0游乐场中运行

发布时间:2020-12-14 05:33:16 所属栏目:百科 来源:网络整理
导读:使用 Swift 3.0在游乐场工作我有这个代码: struct Test { func run() { var timer = Timer.scheduledTimer(withTimeInterval: 1,repeats: false) { timer in print("pop") } }}let test = Test()test.run() 但没有什么是打印到控制台.我已经阅读了How can I
使用 Swift 3.0在游乐场工作我有这个代码:
struct Test {
    func run() {
        var timer = Timer.scheduledTimer(withTimeInterval: 1,repeats: false) { timer in
            print("pop")
        }
    }
}

let test = Test()
test.run()

但没有什么是打印到控制台.我已经阅读了How can I use NSTimer in Swift?,我在网上的答案和教程中看到的计时器的大部分用法涉及一个选择器,所以我尝试了这个:

class Test {
    func run() {
        var timer = Timer.scheduledTimer(timeInterval: 0.4,target: self,selector: #selector(self.peep),userInfo: nil,repeats: false)
    }

    @objc func peep() {
        print("peep")
    }
}

let test = Test()
test.run()

似乎仍然没有打印到控制台.如果我添加timer.fire(),那么我得到控制台打印,但显然这违背了目的.我需要更改什么才能让计时器运行?

编辑:

因此,在为我的Test结构调用run方法后添加CFRunLoopRun()就可以了.非常感谢那些回答的人,特别是@AkshayYaduvanshi(他的评论指向我CFRunLoopRun())和@JoshCaswell(他的答案提出了我的计时器仅适用于运行循环的事实).

您需要启动一个运行循环.
RunLoop.main.run(until: Date(timeIntervalSinceNow: 3))

除非有工作运行循环接受输入,否则计时器不会执行任何操作.该计划只是结束.

Timer reference:

Timers work in conjunction with run loops. […] it fires only when one of the run loop modes to which the timer has been added is running and able to check if the timer’s firing time has passed.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读