[英]In Swift, what is the easiest way to call a method in 5 seconds (non-blocking)?
我有這個,但似乎太復雜了:
var connectionTimer = MZTimerLabel(timerType: MZTimerLabelTypeTimer)
connectionTimer.delegate = self
connectionTimer.tag = 0
connectionTimer.setCountDownTime(5)
connectionTimer.start()
func timerLabel(timerLabel: MZTimerLabel!, finshedCountDownTimerWithTime countTime: NSTimeInterval) {
self.callFinished()
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC), dispatch_get_main_queue()) {
self.callFinished()
}
這是功能強大且用途廣泛的庫Grand Central Dispatch的一部分,該庫將使您不僅可以執行延遲,還可以執行各種並發操作,幾乎可以肯定其中包含線程錯誤! 幸運的是,由於在您的情況下您正在回調主隊列,因此您的代碼都不會同時執行,因此在這種情況下無需擔心。
嘗試這個
let delayTimer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: Selector("delayed"), userInfo: nil, repeats: false)
func delay() { println ("hi") }
五秒鍾后它將呼叫delay
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.