NSTimer サンプル
サンプルで動作を確認 コピーペーストで確認できます。
// タイマーへ渡すオブジェクトを作成
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)
// タイマーの作成
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
// タイマーを作成して実行
NSTimer.scheduledTimerWithTimeInterval(
// 繰り返しの間隔
1.0,
// セレクターのメッソドがあるインスタンス
target: self,
// 呼び出すメソッド名
selector: Selector("timerUpdate:"),
// タイマーへ渡すオブジェクト
userInfo: dictionary,
// リピートするかしないか
repeats: true
)
メソッド
■ タイマーを開始
func fire()
// タイマー開始 timer.fire()
■ タイマーを停止
func invalidate()
// タイマーを停止 timer.invalidate()
プロパティ
■ タイマーの状態を取得します。
var valid: Bool { get }
// タイマーの状態 print(timer.valid)
■ タイマーの開始時間を設定
@NSCopying var fireDate: NSDate
// タイマーの開始時間を設定 timer.fireDate = date
■ タイマーのインターバルを取得
var timeInterval: NSTimeInterval { get }
// タイマーのインターバルを取得 print(timer.timeInterval)
■ 設定されたオブジェクトを取得
var userInfo: AnyObject? { get }
// 設定されたオブジェクトを取得 let dictionary = timer.userInfo as! Dictionary // 内容を表示 print(dictionary["Message"])
■
var tolerance: NSTimeInterval
おすすめの本
