倒数计时器不会在00:00:00:00:00停止

时间:2014-08-09 16:43:58

标签: ios timestamp nstimer nscalendar

我正在使用Xcode 5.1并且有一个倒数计时器,它不会在00:00:00:00停止并继续倒数到负数请你能帮助代码显示如下:

请注意,datelabel.text是计时器出现的地方。

-(void)updatelabel{
    NSCalendar *calender= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *components = [calender components:units  fromDate:[NSDate date] toDate:destinationdate options:1];

    [datelabel setText:[NSString stringWithFormat:@"%d%c %d%c %d%c %d%c %d%c", [components month], 'm',[components day], 'd',[components hour], 'h',[components minute], 'm',[components second], 's']];
}


if ([store.offer isEqual:@"No"] || [store.offerexp isEqual:@"3600"] ) {
    datelabel.text =@"xx";
} else {
    destinationdate = [NSDate dateWithTimeIntervalSince1970:store.offerexp.intValue];

    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updatelabel) userInfo:nil repeats:YES];

    NSLog(@"destination%@",destinationdate);
}

NSTimeInterval TimeStamp = [[NSDate date] timeIntervalSince1970];

1 个答案:

答案 0 :(得分:0)

到达destinationdate时停止计时器。

- (void)updateLabel:(NSTimer *)timer {
    NSDate *now = [NSDate date];
    if ([now compare:destinationdate] != NSOrderedAscending) {
        NSCalendar *calender= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        int units = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        NSDateComponents *components = [calender components:units  fromDate:now toDate:destinationdate options:1];

        [datelabel setText:[NSString stringWithFormat:@"%dm %dd %dh %dm %ds", [components month], [components day], [components hour], [components minute], [components second]]];
    } else {
        [timer invalidate];
        dateLabel.text = @"0m 0d 0h 0m 0s";
    }
}

并将计时器选择器更新为@selector(updateLabel:)而不是@selector(updatelabel)

另请注意,格式字符串可以直接包含时间单位。

注意 - 我可能会向后检查if。它可能需要NSOrderedDescending