Swift 使用計時器
在Swift中,計時器用于創(chuàng)建重復任務以安排延遲工作。愛掏網(wǎng) - it200.com它是一個類,以前被稱為NSTimer。愛掏網(wǎng) - it200.comSwift的計時器類提供了一種靈活的方式來安排將來要發(fā)生一次或多次的工作。愛掏網(wǎng) - it200.com
讓我們看看如何使用運行循環(huán)來創(chuàng)建重復和非重復計時器,如何跟蹤計時器,并且如何減少它們的能量和功耗。愛掏網(wǎng) - it200.com
我們可以使用以下語法創(chuàng)建和啟動一個重復計數(shù)器:
語法
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
讓我們看一個示例來演示如何創(chuàng)建一個重復計數(shù)器:
示例
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fire), userInfo: nil, repeats: true)
@objc func fire()
{
print("FIRE!!!")
}
在上面的示例中,
- 使用 Timer.scheduledTimer(…) 類方法創(chuàng)建了一個定時器。愛掏網(wǎng) - it200.com該方法的返回值賦給常量timer。愛掏網(wǎng) - it200.com現(xiàn)在,這個常量包含一個對定時器的引用,稍后將會用到。愛掏網(wǎng) - it200.com
- scheduledTimer()的參數(shù)是間隔為1秒的定時器。愛掏網(wǎng) - it200.com它使用了一種稱為目標-動作(target-action)的機制,一些設置為nil的userInfo,以及參數(shù)repeats設置為true。愛掏網(wǎng) - it200.com
- 我們還編寫了一個名為fire()的函數(shù)。愛掏網(wǎng) - it200.com這個函數(shù)在定時器觸發(fā)時調(diào)用,大約每秒一次。愛掏網(wǎng) - it200.com通過將target設置為self,selector設置為#selector(fire),你指示每當定時器觸發(fā)時,需要調(diào)用self的fire()函數(shù)。愛掏網(wǎng) - it200.com
參數(shù)解釋
在這個示例中,使用了5個參數(shù)來創(chuàng)建定時器。愛掏網(wǎng) - it200.com
- timeInterval: 它指定了定時器觸發(fā)之間的間隔,單位為秒,類型為Double。愛掏網(wǎng) - it200.com
- target: 它指定了應該在其上調(diào)用選擇器函數(shù)的類實例。愛掏網(wǎng) - it200.com
- selector: 它指定了定時器觸發(fā)時要調(diào)用的函數(shù),使用了#selector(…)。愛掏網(wǎng) - it200.com
- userInfo: 它指定了一個包含要提供給選擇器的數(shù)據(jù)的字典,或者為nil。愛掏網(wǎng) - it200.com
- repeats: 它指定了該定時器是重復還是非重復。愛掏網(wǎng) - it200.com
創(chuàng)建一個非重復的定時器
要創(chuàng)建一個非重復的定時器,只需將 repeats 參數(shù)設置為 false 。愛掏網(wǎng) - it200.com定時器只會觸發(fā)一次,并在觸發(fā)后立即使自身失效。愛掏網(wǎng) - it200.com
示例
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(fire), userInfo: nil, repeats: false)
@objc func fire()
{
print("FIRE!!!")
}
注意:上述代碼必須在類上下文中運行,例如在視圖控制器類中。愛掏網(wǎng) - it200.comfire()函數(shù)是類的一部分,self指的是當前類實例。愛掏網(wǎng) - it200.com
使用閉包創(chuàng)建一個計時器
let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { timer in
print("FIRE!!!")
})
在上面的代碼中,最后一個參數(shù)塊接受一個閉包。愛掏網(wǎng) - it200.com閉包有一個參數(shù)是計時器本身。愛掏網(wǎng) - it200.com
在這里,使用@objc屬性是因為它使得fire()函數(shù)在Objective-C中可用。愛掏網(wǎng) - it200.com計時器類是Objective-C運行時的一部分,這就是我們使用@objc屬性的原因。愛掏網(wǎng) - it200.com
重復和非重復計時器之間的區(qū)別
在創(chuàng)建計時器時,必須指定計時器是重復還是非重復。愛掏網(wǎng) - it200.com重復和非重復計時器之間的主要區(qū)別是:
非重復計時器 只會觸發(fā)一次,然后自動使自身無效,因此防止計時器再次觸發(fā)。愛掏網(wǎng) - it200.com
重復計時器 會觸發(fā)并在同一次運行循環(huán)上重新調(diào)度自己。愛掏網(wǎng) - it200.com重復計時器總是根據(jù)預定的觸發(fā)時間進行調(diào)度,而不是實際的觸發(fā)時間。愛掏網(wǎng) - it200.com
例如,如果一個計時器被預定在特定的時間觸發(fā),并且之后每10秒一次,即使實際觸發(fā)時間延遲,預定的觸發(fā)時間仍然會落在原始的10秒間隔上。愛掏網(wǎng) - it200.com