★ 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)