我在Swift中使用Timer,不确定它是如何工作的。我试图扫描2秒钟,连接到外围设备,然后结束扫描。我有以下代码,其中connectToPeripheralstartScanendScan是同一类中的函数。

    startScan()
Timer(timeInterval: 2, target: self, selector: #selector(connectToPeripheral), userInfo: nil, repeats: false)
    endScan()

选择器如何在计时器中工作?在代码调用计时器之后,代码是仅执行选择器而不是调用下一步的代码,还是仅在选择器完成运行后才调用下一步的代码?基本上,我要问的是有关计时器及其选择器的事件周期是多少。

最佳答案

在指定为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
输出:

08-05 23:03
查看更多