//每一秒执行一次,在主线程,common模式。立即执行
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View{
VStack {
Text("Hello, World!")
.onReceive(timer) { //onReceive()的新修饰符来手动捕获公告,接受发布者作为其第一个参数,并接受要作为其第二个函数运行的函数,并且它将确保在发布者发送其更改通知时都会调用该函数。
time in
print("The time is now \(time)")
}
}
}
停止计时器:我们制作的timer
属性是一个自动连接的发布者,因此我们需要转到其上游发布者来查找计时器本身。从那里我们可以连接到计时器发布者,并要求它取消自身。
self.timer.upstream.connect().cancel()
计时器容差0.5秒,这就个计时器就是确定,
let timer = Timer.publish(every: 1, tolerance: 0.5, on: .main, in: .common).autoconnect()
Common Modes 不是一种真正的RunLoop Mode,是一种伪模式,指可以在标记为Common Modes的 RunLoop 模式下运行
目前被标记为 Common Modes 的模式: kCFRunLoopDefaultMode,UITrackingRunLoopMode
所以类似 Timer
添加到 Common Mode 的时候,并不是真正的添加了,他查找他的modes, 然后给他的modes 添加 Timer
即实际上,Timer
添加到了 Default 和 Tracking模式。