1

すべて異なる時間(25、50、1分、1分30秒...)で開始する複数のタイマーを作成したいのですが、0に達したときに停止し、ゼロに達したときに停止する方法がわかりません。別のビューへの「プレーヤー」。

これが私の.hファイルです

@interface ViewController :UIViewController {

IBOutlet UILabel *seconds;

NSTimer *timer;

int MainInt;
}

@end

そしてここに私の.mファイルがあります

@implementation ViewController

-(void)countDownDuration {

MainInt -= 1;

seconds.text = [NSString stringWithFormat:@"%i", MainInt];

}

-(IBAction)start:(id)sender {

MainInt = 25;

timer = [NSTimer scheduledTimerWithTimeInterval:1.0

                                         target:self
                                       selector:@selector(countDownDuration)
                                       userInfo:nil
                                        repeats:YES];
}

@end
4

1 に答える 1

5

NSTimerはこれを自動的に行いませんが、countDownDurationメソッドに追加するのは簡単です。例えば:

-(void)countDownDuration {
  MainInt -= 1;
  seconds.text = [NSString stringWithFormat:@"%i", MainInt];
  if (MainInt <= 0) {
    [timer invalidate];
    [self bringThePlayerToAnotherView];
  }
}

もちろん、複数のタイマーを作成する必要があります。それぞれを異なる変数に格納し、それぞれに異なるセレクターを与えることができます。しかし、NSTimerのドキュメントを見ると、コールバックメソッドは実際にはタイマーオブジェクトをセレクターとして受け取ります。あなたはそれを無視していますが、そうすべきではありません。

その間、タイマーのuserInfoとして任意のタイプのオブジェクトを保存できるため、タイマーごとに個別の現在のカウントダウン値を格納するのに適した場所です。

したがって、次のようなことができます。

-(void)countDownDuration:(NSTimer *)timer {
  int countdown = [[timer userInfo] reduceCountdown];
  seconds.text = [NSString stringWithFormat:@"%i", countdown];
  if (countdown <= 0) {
    [timer invalidate];
    [self bringThePlayerToAnotherView];
  }
}

-(IBAction)start:(id)sender {
  id userInfo = [[MyCountdownClass alloc] initWithCountdown:25];
  timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                           target:self
                                         selector:@selector(countDownDuration:)
                                         userInfo:userInfo
                                          repeats:YES];
}

私はいくつかの詳細を書き残しました(の定義のようにMyCountdownClass—メソッドを含めるinitWithCountdown:必要reduceCountdownがあり、それは正しいことをします)が、それらはすべてかなり単純なはずです。(また、おそらく、カウントダウン値以上のものを格納するuserInfoが必要です。たとえば、各タイマーがプレーヤーを別のビューに送信する場合は、そこにもビューを隠しておく必要があります。)

PS、今必要なことに注意してください@selector(countDownDuration:)。ObjCの初心者は、これを常に台無しにします。countDownDuration:countDownDurationは完全に無関係なセレクターです。

PPSの場合、の完全な定義がMyCountdownClassで表示される必要がありますcountDownDuration:(同じセレクターを持つ他のクラスがない場合)。物事をより明確にするために、 userInfotoの結果を明示的にキャストすることをお勧めします。MyCountdownClass *

于 2012-09-20T00:42:58.607 に答える