我有一个NSTimer对象如下:
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
Run Code Online (Sandbox Code Playgroud)
我想把超时给我的计时器.也许你知道android中的postdelayed方法.我想要同样的东西的快速版本.我怎样才能做到这一点 ?
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()
Run Code Online (Sandbox Code Playgroud)
在操场上试试吧.它将对函数的每次传递应用不同的延迟.
| 归档时间: |
|
| 查看次数: |
2214 次 |
| 最近记录: |