objective-c - NSTimer 时间增量

标签 objective-c ios nstimer

我是 iOS 平台 obj-C 的初学者,正在尝试构建一些简单的项目来奠定我的基础。

我有一个按钮可以增加标签的 NSTimer 时间,但是当我使用 NSLog 记录时间时,它使用实现时间增量之前的值。我需要能够记录更新的时间(增量后),因为我需要该值,并且在解决这部分后我将在 IBAction 中实现更多功能。

例如,在我按下 15 分钟时,NSLog 会将其读取为“00:15:00.0”而不是“00:35:00.0”。

- (IBAction)onSkipPressed:(id)sender {
    startDate = [startDate dateByAddingTimeInterval:-1200];
    NSLog(@"%@",self.timeLabel.text);
}

有人知道这个问题的原因吗?如果我在 15 分钟调用此 IBAction,我应该如何解决这个问题,以便 NSLog 将其读取为“00:35:00.0”。

编辑 - 开始按钮将启动计时器,timeLabel 将获取字符串。抱歉错过了这么重要的细节。我认为项目中没有任何其他代码与此功能相关。感谢您向我指出这一点。

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

我的 IBAction 来触发计时器

- (IBAction)onStartPressed:(id)sender {
    startDate = [NSDate date];

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

    //hide start button and show timeLabel
    startButton.hidden=true;
    timeLabel.hidden=false;

}

最佳答案

我回去对涉及 NSTimer 的教程做了一些修改。事实证明我所缺少的只是 1 行 [self updateTimer]

- (IBAction)onSkipPressed:(id)sender {
    startDate = [startDate dateByAddingTimeInterval:-1200];
    [self updateTimer];
    NSLog(@"%@",self.timeLabel.text);
}

这解决了我的问题,并且 timeLabel.text 已更新,以便我记录信息。

关于objective-c - NSTimer 时间增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13065847/

相关文章:

objective-c - 我如何在没有 Bonjour 的情况下找到所有网络设备?

ios - Firebase 查询未触发以调用它们

ios - UIImagePicker 仅适用于 iPhone 6 plus 上的前置摄像头

ios - NSTimer 有错误消息?

ios - 在 NSOperationQueue 线程中运行 NSTimer

iphone - Reminders.app UIScrollView 滚动解释。

ios - 在运行时更改自动布局

ios - UINavigationBar 在 Action Extension 中的旋转高度错误

iphone - UITextView 文字垂直对齐

objective-c - iOS:一段时间后在后台终止应用程序