Swift中的定时器是如何工作的?

7

我正在使用Swift中的计时器,不确定它的工作方式。我尝试扫描2秒钟,连接到外围设备,然后结束扫描。以下是代码,其中connectToPeripheralstartScanendScan是同一类中的函数。

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

计时器中的选择器是如何工作的?当代码调用计时器后,它是否仅执行选择器而不调用接下来的任何代码部分,还是在选择器完成运行后才调用接下来的内容?基本上,我想知道计时器及其选择器的事件循环是什么。
1个回答

5

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)

打印("执行继续进行")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接