Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active June 4, 2016 06:13
Show Gist options
  • Save KentarouKanno/976714fbbee0085c1947dc2ae7d23a5e to your computer and use it in GitHub Desktop.
Save KentarouKanno/976714fbbee0085c1947dc2ae7d23a5e to your computer and use it in GitHub Desktop.
NSTimer

NSTimer

★ Scheduled Timer

// タイマーは即時スタート
NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.update(_:)), userInfo: nil, repeats: true)

// 戻り値はNSTimer
let timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.update(_:)), userInfo: nil, repeats: true)

// Run loopに登録する(アニメーション中にタイマーが停止しない)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)

// 呼び出されるメソッド
func update(timer: NSTimer) {
  print("call!")
  
  // タイマーが動いているかの判定
  var isValid = timer.valid
  
  // タイマーを止める
  // timer.invalidate()
}

★ Unscheduled Timer

let timer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(self.update(_:)), userInfo: nil, repeats: true)

// Run loopに登録してタイマー開始
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)

// or 

// タイマー開始
timer.fire()


// UserInfo付き
timer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(self.update(_:)), userInfo: ["info1":"value","info2": 123], repeats: true)

func update(timer: NSTimer) {
    if let info1 = timer.userInfo?["info1"] as? String, let info2 = timer.userInfo?["info2"] as? Int {
        print("info1 = \(info1), info2 = \(info2)")
        //=> info1 = value, info2 = 123
    }
}


// タイマーの開始時間を設定する(例は5秒後に開始)
timer = NSTimer(fireDate: NSDate(timeIntervalSinceNow: 5), interval: 1.0, target: self, selector: #selector(self.update(_:)), userInfo: nil, repeats: true)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment