[英]How to put timeout to NSTimer in swift?
我有一个NSTimer对象,如下所示:
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
我想将超时设置为计时器。 也许您知道android中的postdelayed方法。 我想要同一件事的快速版本。 我怎样才能做到这一点 ?
NSTimer
不适合可变间隔时间。 您将其设置为一个指定的延迟时间,并且无法更改。 与每次停止和启动NSTimer
相比,更优雅的解决方案是使用dispatch_after
。
借用Matt的答案 :
// 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()
在操场上尝试一下。 它将对函数的每次通过施加不同的延迟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.