【Swift】NSTimer | ポケットリファレンス、サンプル付き (Xcode)
NSTimer サンプル
サンプルで動作を確認 コピーペーストで確認できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
// タイマーへ渡すオブジェクトを作成 let dictionary : Dictionary = ["Message" :"Hello" , "Message2" :"Hello2"] // タイマーを作成して実行 NSTimer.scheduledTimerWithTimeInterval( // 繰り返しの間隔 1.0, // セレクターのメッソドがあるインスタンス target: self, // 呼び出すメソッド名 selector: Selector("timerUpdate:"), // タイマーへ渡すオブジェクト userInfo: dictionary, // リピートするかしないか repeats: true ) // タイマーの作成 let timer : NSTimer = NSTimer( // 繰り返しの間隔 timeInterval: 0.1, // セレクターのメッソドがあるインスタンス target: self, // 呼び出すメソッド名 selector: Selector("timerUpdate2:"), // タイマーへ渡すオブジェクト userInfo: dictionary, // リピートするかしないか repeats: true ) // タイマー開始時間の日付オブジェクト作成 var date : NSDate = NSDate(); // 60 秒後を設定 date = NSDate(timeIntervalSinceNow: 60); // タイマーの開始時間を設定 timer.fireDate = date // タイマー開始 timer.fire() // タイマーのインターバルを取得 print(timer.timeInterval) // print(timer.tolerance) // タイマーの状態 print(timer.valid) // タイマーを停止 timer.invalidate() |
NSTimer 概要
タイマー利用時に使用します。
イニシャライザー (初期化)
■ スケジュールタイマーを作成します。自動で開始されます。
init(timeInterval ti: NSTimeInterval,
target aTarget: AnyObject,
selector aSelector: Selector,
userInfo userInfo: AnyObject?,
repeats yesOrNo: Bool)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// タイマーの作成 let timer : NSTimer = NSTimer( // 繰り返しの間隔 timeInterval: 0.1, // セレクターのメッソドがあるインスタンス target: self, // 呼び出すメソッド名 selector: Selector("timerUpdate2:"), // タイマーへ渡すオブジェクト userInfo: dictionary, // リピートするかしないか repeats: true ) |
■ スケジュールタイマーを作成します。
class func scheduledTimerWithTimeInterval(
_ ti: NSTimeInterval,
target aTarget: AnyObject,
selector aSelector: Selector,
userInfo userInfo: AnyObject?,
repeats yesOrNo: Bool) -> NSTimer
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// タイマーを作成して実行 NSTimer.scheduledTimerWithTimeInterval( // 繰り返しの間隔 1.0, // セレクターのメッソドがあるインスタンス target: self, // 呼び出すメソッド名 selector: Selector("timerUpdate:"), // タイマーへ渡すオブジェクト userInfo: dictionary, // リピートするかしないか repeats: true ) |
メソッド
■ タイマーを開始
func fire()
1 2 |
// タイマー開始 timer.fire() |
■ タイマーを停止
func invalidate()
1 2 |
// タイマーを停止 timer.invalidate() |
プロパティ
■ タイマーの状態を取得します。
var valid: Bool { get }
1 2 |
// タイマーの状態 print(timer.valid) |
■ タイマーの開始時間を設定
@NSCopying var fireDate: NSDate
1 2 |
// タイマーの開始時間を設定 timer.fireDate = date |
■ タイマーのインターバルを取得
var timeInterval: NSTimeInterval { get }
1 2 |
// タイマーのインターバルを取得 print(timer.timeInterval) |
■ 設定されたオブジェクトを取得
var userInfo: AnyObject? { get }
1 2 3 4 |
// 設定されたオブジェクトを取得 let dictionary = timer.userInfo as! Dictionary // 内容を表示 print(dictionary["Message"]) |