Mer*_*tio 8 cocoa nstimer swift swift-playground
使用Swift 3.0在游乐场工作我有这个代码:
struct Test {
func run() {
var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { timer in
print("pop")
}
}
}
let test = Test()
test.run()
Run Code Online (Sandbox Code Playgroud)
但没有什么是打印到控制台.我读过如何在Swift中使用NSTimer?我在网上的答案和教程中看到的计时器的大部分用法涉及一个选择器,所以我尝试了这个:
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()
Run Code Online (Sandbox Code Playgroud)
似乎仍然没有打印到控制台.如果我添加timer.fire()
,那么我得到控制台打印,但显然这违背了目的.我需要更改什么才能让计时器运行?
编辑:
所以CFRunLoopRun()
在我run
为我的Test
struct 调用方法之后添加就可以了.非常感谢那些回答的人,特别是@AkshayYaduvanshi(他的评论指向我CFRunLoopRun()
)和@JoshCaswell(他的答案提出了我的计时器只适用于运行循环的事实).
aya*_*aio 23
如果允许Playground通过PlaygroundSupport
以下方式无限期运行,则第一个版本可以正常运行:
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
let timer = Timer.scheduledTimer(withTimeInterval: 3, repeats: true) { timer in
print("Timer Fired at: \(timer.fireDate)")
}
Run Code Online (Sandbox Code Playgroud)
手动添加运行循环也有效,有时可能需要,但在这种情况下,这个简单的指令足以使Timer正常工作.
你需要开始一个运行循环.
RunLoop.main.run(until: Date(timeIntervalSinceNow: 3))
Run Code Online (Sandbox Code Playgroud)
除非有工作运行循环接受输入,否则计时器不会执行任何操作.该计划只是结束.
定时器与运行循环一起使用.[...]仅当已添加计时器的其中一个运行循环模式正在运行并且能够检查计时器的触发时间是否已经过去时,它才会触发.