LoginSignup
10

More than 5 years have passed since last update.

NSTimerを同時に複数使う場合

Last updated at Posted at 2015-03-23

条件

  • Objective-C(まだ、Swift勉強中ですので、すみません。)
  • NSTimerを同時に複数使う

解決案

NSTimerのtimerWithTimeIntervalメソッドを使用すれば解決
それぞれのNSTimerインスタンスを以下のように宣言して使えばよい.
追記あり(ページ下の追記項目かコメントを見てください[2015/03/23])

test.m
- (void)initAllTimer{
  //タイマーそれぞれ初期化
  [self performSelectorInBackground:@selector(initTimer1) withObject:nil];
  [self performSelectorInBackground:@selector(initTimer2) withObject:nil];
}

- (void)initTimer1{
 //1:timerWithTimeIntervalでインスタンス作成
 NSTimer *timer1 = [NSTimer
                         timerWithTimeInterval:20
                         taraget:self
                         selector:@selector(hoge1)
                         userInfo:nil
                         repeats:NO
                        ];

 //2:タイマーが発動するように実行ループに追加
 id runLoop1 = [NSRunLoop currentRunLoop];
 [runLoop1 addTimer:timer1 forMode:NSDefaultRunLoopMode];
 [runLoop1 run];
}

- (void)initTimer2{
 //1:timerWithTimeIntervalでインスタンス作成
 NSTimer *timer2 = [NSTimer
                         timerWithTimeInterval:350
                         taraget:self
                         selector:@selector(hoge2)
                         userInfo:nil
                         repeats:NO
                        ];

 //2:タイマーが発動するように実行ループに追加
 id runLoop2 = [NSRunLoop currentRunLoop];
 [runLoop2 addTimer:timer2 forMode:NSDefaultRunLoopMode];
 [runLoop2 run];
}


-(void)hoge1{
  //20秒後に呼び出されます
}

-(void)hoge2{
  //350秒後に呼び出されます
}

はまりポイント

NSRunLoopのrunメソッドを呼ぶことで、NSTimerのfireメソッドを呼ぶ代わりになる。

追記(2015/03/23)

scheduledTimerWithTimeIntervalメソッドを使うことで、NSRunLoopを明示的に呼ぶ必要はなさそうです。また、NSTimerインスタンス作成をバッググラウンドで呼ぶ必要もなさそうです。まだ、追記の追記があるかも。。。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10