Search code examples
objective-cxcodensdatenstimernstimeinterval

Xcode - setting limit for NSDate CountDown timer


Iam using xCode 4.3.2, In my count-down timer project (code showing below), i want to stop the count-down after 30 seconds. How can i set this limit for my count-down? Could you please help me?

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];
}

Solution

  • Just add to your countDown

    if([[NSDate date] timeIntervalSinceDate:startDate]>=countLimit)
    
    [myTimer invalidate];