我有一个NSTimer对象如下:
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
我想为计时器设置超时。也许你知道安卓中的后期延迟方法。我想要同样的事情的快速版本。我该怎么做?
NSTimer
不适合可变间隔时间。您设置了一个指定的延迟时间,并且无法更改它。比每次都停止和启动NSTimer
更优雅的解决方案是使用 dispatch_after
.
借用马特的回答:
// this makes a playground work with GCD
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
struct DispatchUtils {
static func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
class Alpha {
// some delay time
var currentDelay : NSTimeInterval = 2
// a delayed function
func delayThis() {
// use this instead of NSTimer
DispatchUtils.delay(currentDelay) {
print(NSDate())
// do stuffs
// change delay for the next pass
self.currentDelay += 1
// call function again
self.delayThis()
}
}
}
let a = Alpha()
a.delayThis()
在操场上尝试一下。它将对函数的每次传递应用不同的延迟。