我在Swift中使用Timer并且不确定它是如何工作的。我正在尝试扫描2秒钟,连接到外围设备,然后结束扫描。我有以下代码,其中connectToPeripheral
,startScan
和endScan
是同一类中的函数。
startScan()
Timer(timeInterval: 2, target: self, selector: #selector(connectToPeripheral), userInfo: nil, repeats: false)
endScan()
选择器如何在计时器中工作?在代码调用定时器之后,代码是否仅执行选择器而不是调用接下来的任何代码,或者仅在选择器完成运行后调用接下来的代码?基本上,我问的是关于计时器及其选择器的事件周期是什么。
答案 0 :(得分:4)
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
输出:
打印(“代码已启动”)
TimerTest()。scheduleTimer(2)
print(“执行继续正常”)