3

2秒ごとに何か違うものを10回表示させたいです。Objective-Cでこれを達成するにはどうすればよいですか?

上記の例のように、タイマーを開始してから 2 * 10 秒後に、NSTimer を使用して無効にすることを考えていました。または、ダニを測定する方法はありますか?

または、for ループを検討して performSelector:withDelay: メソッドを使用していました。

どちらが好ましいでしょうか?

4

2 に答える 2

7

NSTimerを使用して、時刻interval2 secondsおよびrepeatsに設定しYESます。

トリガーされた回数をカウントします。Invalidate 10になったら

コード:

[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(trigger:) userInfo:yourObject repeats:YES];

- (void)trigger:(NSTimer *)sender{

    id yourObject = sender.userInfo;

    static int count = 1;

    @try {

        NSLog(@"triggred %d time",count);

        if (count == 10){

            [sender invalidate];
            NSLog(@"invalidated");
        }

    }
    @catch (NSException *exception)
    {
        NSLog(@"%s\n exception: Name- %@ Reason->%@", __PRETTY_FUNCTION__,[exception name],[exception reason]);
    }
    @finally {

        count ++;
    }
}
于 2013-03-14T18:25:01.890 に答える
3

私はあなたの2番目のオプションを使用しました、タイマーは必要ありません

for (int a=0; a<10; a++) {
    [self performSelector:@selector(print) withObject:nil afterDelay:2.0*a];
}


-(void)print
{
    NSLog(@"sth");
}

間隔と繰り返し回数を柔軟にすることができます。

于 2013-03-14T19:21:10.713 に答える