Xcode - NSDate CountDown计时器的设置限制

时间:2012-04-14 09:44:54

标签: objective-c xcode nsdate nstimer nstimeinterval

我使用xCode 4.3.2,在我的倒计时器项目(下面显示的代码)中,我想在30秒后停止倒计时。如何为倒计时设置此限制? 你能帮我吗?

int countLimit=30; //seconds
NSDate *startDate;

- (void)countDown{
    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = -([currentDate timeIntervalSinceDate:startDate]);
    NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"HH:mm:ss"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSString *timeString=[dateFormatter stringFromDate:timerDate];
    self.myCounterLabel.text = timeString;
    [dateFormatter release];
}

- (void)updateCounter{

    self.myCounterLabel.text = @"00:00:00";
    startDate = [[NSDate date]retain];

    myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/10.0
    target:self
    selector:@selector(countDown)
    userInfo:nil
    repeats:YES];
}

1 个答案:

答案 0 :(得分:0)

只需添加到 countDown

即可
if([[NSDate date] timeIntervalSinceDate:startDate]>=countLimit)

[myTimer invalidate];