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

标签 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];

最佳答案

到达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

关于ios - 倒数计时器不会在00:00:00:00:00停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25220797/

相关文章:

c - 获取小时/分钟/秒,无需用户更改系统小时

iPhone 计时器具有最小的误差/漂移

ios - 倒数计时器停止并重置为 0

ios - NSTimer 无效不起作用

ios - 如何更改 iOS 的小数位数?

ios - MapKit map 中的标注是透明的

ios - 使用 NSDictionary 访问 NSJSONSerialization 数据

ios - 单击 UIBar 按钮时删除 TabBar Controller

php - 将日期 dd/mm/yyyy 格式从表单转换为时间戳?

JavaScript 写一个带有过期时间的 cookie