【问题标题】:Comparing dates inside a nstimer selector比较 nstimer 选择器中的日期
【发布时间】:2011-02-08 18:56:29
【问题描述】:

我正在编写一个 countdowtimer 应用程序,例如 iPhone 时钟应用程序中的计时器选项卡。现在我无法比较日期、“现在”和“未来日期”。 所有变量都是合成的并且是非原子的并且保留。 我现在有这个代码。

- (IBAction)startTimer:(id)sender {
    NSLog(@"startTimer");
    pickerView.hidden = YES;
    labelView.hidden  = NO;
    now = [[NSDate alloc] init];
    futureDate = [[NSDate alloc] initWithTimeInterval:picker.countDownDuration sinceDate:now];
    NSLog(@"Dates.\nNow = (%@)  \nfutureDate (%@)", now, futureDate);
    timerLabelUpdater = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(labelUpdater) userInfo:nil repeats:YES];
}

- (void)labelUpdater {
    if ([now timeIntervalSinceDate:futureDate] < 0.0) {
        NSLog(@"YES\nDates.\nNow = (%@)  \nfutureDate (%@)", now, futureDate);
    } else {
        NSLog(@"NO\nNow = (%@)  \nfutureDate (%@)", now, futureDate);
    }
}

调试器信息: 2011-02-08 16:46:02.449 应用程序[22504:207] startTimer 2011-02-08 16:46:02.451 应用程序 [22504:207] 日期。 现在 = (2011-02-08 18:46:02 +0000)
未来日期 (2011-02-08 18:47:02 +0000) 2011-02-08 16:46:03.451 应用程序[22504:207] 是

它一直在“永远”给我肯定。 但是,如果您看到可变时间,那么与我的时钟时间相比,它们在未来是 +2 小时。这是bug吗?

【问题讨论】:

    标签: cocoa-touch ios datetime nsdate


    【解决方案1】:

    对不起,如果我测试了错误的日期,比较变量 now 和 futureDate 时间间隔将永远相同。我在测试中用 [[NSDate alloc] init] 替换了 now 变量。现在代码可以工作了。

    if ([[[NSDate alloc]init] timeIntervalSinceDate:futureDate] < 0.0) {
        NSLog(@"YES\nDates.\nNow = (%@)  \nfutureDate (%@)", now, futureDate);
    } else {
        NSLog(@"NO\nNow = (%@)  \nfutureDate (%@)", now, futureDate);
    }
    

    抱歉这个愚蠢的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-28
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2021-01-31
      相关资源
      最近更新 更多