-1

有人想教我如何使用循环过程NSTimer吗?我有 2 个进程计时器要做,timer1 和 timer2 重复到由按钮触发的 n 循环(timer1 -> timer2 -> timer1 -> timer2 等等,直到 n 循环)。我是 xcode 的新手。请教我。两个计时器都有用户输入。如果可能的话,请给我一个例子。

我的代码应该是这样的。如果我错了,请纠正我

- (void) timer2Elapsed:(NSTimer *) timer;
{
    ...

    displayCountDown.text = [NSString stringWithFormat:@"%d : %d : %d", hour , minute, second];
}

- (void)timer1Elapsed: (NSTimer *) timer;
{
    ...

    displayCountDown.text = [NSString stringWithFormat:@"%d : %d : %d", hour , minute, second];
}

我触发倒计时的按钮:

- (IBAction)startBtn:(id)sender {
        endSetTime = [NSDate timeIntervalSinceReferenceDate] + totalSecondTime;
        endSetRest = [NSDate timeIntervalSinceReferenceDate] + totalSecondRest;
        countdownTimer = [NSTimer scheduledTimerWithTimeInterval: 0.99 target: self selector: @selector(timer1Elapsed:) userInfo: nil repeats: YES];

}

这里有人告诉我使用这段代码,但我不知道我应该在里面写什么以及放在哪里?他说循环?我不知道?以及如何在我的按钮内连接该代码?

+ (void) startTimer:(id)timer
{
    static int numberOfTimes = 0;
    if(numberOfTimes >= 5)
    {
        numberOfTimes = 0;
        return;
    }
    numberOfTimes ++;

    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timer1Elapsed:) userInfo:nil repeats:NO];
}
4

1 回答 1

0

忘记计时器。使用 performSelector:withObject:afterDelay: 选择器。

@interface CECountdown : NSObject {
    NSDate *_startDate;
    NSTimeInterval _countdownInterval;
}

@end

@implementation CECountdown

- (id)initWithCountdownInterval:(NSTimeInterval)interval {
    self = [super init];

    if(self) {
        _countdownInterval = interval;
        _startDate = [[NSDate date] retain];
    }

    return self;
}

- (void)dealloc {
    [_startDate release];

    [super dealloc];
}

- (void)method0 {
    // Do something
    [self performSelector:@selector(method1) withObject:nil afterDelay:0.3];
    [self checkTimeout];
}

- (void)method1 {
    // Do something
    [self performSelector:@selector(method0) withObject:nil afterDelay:0.3];    
    [self checkTimeout];
}

- (void)invalidate {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(method1) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(method2) object:nil];
}

- (void)checkTimeout {
    if([NSDate timeIntervalSinceReferenceDate] - [_startDate timeIntervalSinceReferenceDate] > _countdownInterval) {
        [self invalidate];
    }
}

- (void)didTapStartButton:(id)sender {
    [self performSelector:@selector(method1) withObject:nil afterDelay:0.3];
}

@end
于 2012-06-27T08:36:10.500 回答