2016-02-05 132 views
0

我有一個的NSTimer如下對象:如何把超時時間設置爲NSTimer?

var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateTimer", userInfo: nil, repeats: true) 

我希望把超時到我的定時器。也許你知道android中的postdelayed方法。我想要相同的東西的迅速版本。我怎樣才能做到這一點 ?

+0

超時應該做什麼?對於那些不知道postdelayed的用戶。在x時間之後,計時器應該停止? –

+0

是不是定義了一個定時器? – Russell

+0

我想延遲計時器3秒。那麼它可以再次工作 – sorunluadam

回答

6

NSTimer不適用於可變間隔時間。你用一個指定的延遲時間來設置它,你不能改變它。比停止並開始NSTimer每一次更優雅的解決方案是使用dispatch_after

Matt's answer借鑑:

// 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() 

嘗試在一個操場。 它將爲函數的每次傳遞應用不同的延遲。

+1

這對我來說非常有幫助。感謝您的關注 – sorunluadam