Swift 中的计时器如何工作?
How does a Timer work in Swift?
我在 Swift 中使用定时器,但不确定它是如何工作的。我正在尝试扫描 2 秒,连接到外围设备,然后结束扫描。我有以下代码,其中 connectToPeripheral
、 startScan
和 endScan
是同一个 class.
中的函数
startScan()
Timer(timeInterval: 2, target: self, selector: #selector(connectToPeripheral), userInfo: nil, repeats: false)
endScan()
计时器中的选择器是如何工作的?代码调用计时器后,代码是否仅执行选择器而不调用接下来的任何代码,还是仅在选择器完成 运行 后才调用接下来的代码?基本上,我问的是关于定时器及其选择器的事件周期是什么。
A Timer
在指定为 timeInterval
的时间过去后调用其选择器输入参数中指定的方法。 Timer
不影响其余代码的生命周期(当然除了在选择器中指定的方法),所有其他函数都正常执行。
查看这个最小的 Playground 示例:
class TimerTest: NSObject {
var timer:Timer?
func scheduleTimer(_ timeInterval: TimeInterval){
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(TimerTest.timerCall), userInfo: nil, repeats: false)
}
func timerCall(){
print("Timer executed")
}
}
print("Code started")
TimerTest().scheduleTimer(2)
print("Execution continues as normal")
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
输出:
print("Code started")
TimerTest().scheduleTimer(2)
print("Execution continues as normal")
我在 Swift 中使用定时器,但不确定它是如何工作的。我正在尝试扫描 2 秒,连接到外围设备,然后结束扫描。我有以下代码,其中 connectToPeripheral
、 startScan
和 endScan
是同一个 class.
startScan()
Timer(timeInterval: 2, target: self, selector: #selector(connectToPeripheral), userInfo: nil, repeats: false)
endScan()
计时器中的选择器是如何工作的?代码调用计时器后,代码是否仅执行选择器而不调用接下来的任何代码,还是仅在选择器完成 运行 后才调用接下来的代码?基本上,我问的是关于定时器及其选择器的事件周期是什么。
A Timer
在指定为 timeInterval
的时间过去后调用其选择器输入参数中指定的方法。 Timer
不影响其余代码的生命周期(当然除了在选择器中指定的方法),所有其他函数都正常执行。
查看这个最小的 Playground 示例:
class TimerTest: NSObject {
var timer:Timer?
func scheduleTimer(_ timeInterval: TimeInterval){
timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(TimerTest.timerCall), userInfo: nil, repeats: false)
}
func timerCall(){
print("Timer executed")
}
}
print("Code started")
TimerTest().scheduleTimer(2)
print("Execution continues as normal")
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
输出:
print("Code started")
TimerTest().scheduleTimer(2)
print("Execution continues as normal")