Swift 計時器
在開發移動應用程序時,有時需要安排一些任務在將來發生。愛掏網 - it200.comSwift提供了一個計時器類,我們可以在一定時間間隔后執行任務。愛掏網 - it200.com
在這篇文章中,我們將討論如何使用swift計時器來安排任務。愛掏網 - it200.com同時,我們還將討論如何使用重復和非重復計時器。愛掏網 - it200.com
下面的代碼創建并運行了一個重復計時器。愛掏網 - it200.com
let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
上述代碼要求在同一類中定義一個@objc方法fireTimer()。愛掏網 - it200.com
@objc func fireTimer(){
debugPrint("Timer fired")
}
在這里,我們已經將定時器設置為每1秒執行一次。愛掏網 - it200.com因此,fireTimer()方法將每1秒被調用一次。愛掏網 - it200.com然而,在創建重復定時器時,Swift允許我們定義閉包,如下所示。愛掏網 - it200.com
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
debugPrint("Timer fired")
}
兩個初始化方法都用于返回創建的計時器。愛掏網 - it200.com然而,我們可以將返回值存儲在屬性中,以便稍后可以使其無效。愛掏網 - it200.com
創建非重復計時器
如果我們只想運行代碼一次,就需要創建非重復計時器。愛掏網 - it200.com為此,我們需要在創建計時器時將repeats屬性更改為false。愛掏網 - it200.com
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false) { (timer) in
debugPrint("Timer fired")
}
結束一個計時器
我們可以通過調用計時器對象的invalidate()方法來結束一個已存在的計時器。愛掏網 - it200.com考慮以下示例,它每秒鐘運行一次代碼,共運行四次,然后使計時器失效。愛掏網 - it200.com
var count = 0
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (timer) in
debugPrint("Timer fired")
count = count + 1
if(count == 4){
timer.invalidate()
}
}
它在控制臺上打印以下輸出。愛掏網 - it200.com
"Timer fired"
"Timer fired"
"Timer fired"
"Timer fired"
以上示例中,我們在創建計時器時使用了閉包。愛掏網 - it200.com我們也可以在這里使用方法的方式。愛掏網 - it200.com但是,在方法中無效化計時器對象如下所示。愛掏網 - it200.com
class TimerExample:NSObject{
var count = 0
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
@objc func fireTimer(){
debugPrint("Timer Fired")
count = count + 1
if(count == 4){
timer.invalidate()
}
}
}