【问题标题】:Time change notification (hours and minutes) in objcobjc 中的时间更改通知(小时和分钟)
【发布时间】:2015-08-08 13:24:33
【问题描述】:

是否有最佳做法在时间更改时获取通知?

我正在使用NSTimer 每 0,002 秒检查一次时间是否发生变化(小时和分钟,而不是秒和毫秒),以保持我的应用程序中的标签每分钟与手机时钟同步。

希望有更好的解决方案。

谢谢

【问题讨论】:

  • NSTimer 是您任务的不错解决方案,您还可以收听 UIApplicationSignificantTimeChangeNotification(当用户在设置中设置时间时发送)。但是,如果您的计时器的间隔非常小,则不需要通知观察

标签: objective-c time nstimer clock clock-synchronization


【解决方案1】:

设置从下一整分钟开始的循环计时器:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)        

    let nextMinuteDate =  NSCalendar.currentCalendar().nextDateAfterDate(NSDate(), matchingUnit: .Second, value: 0, options: [.MatchNextTime])!
    self.minuteDidChangeTimer = NSTimer(fireDate: nextMinuteDate, interval: 60.0, target: self, selector: "minuteDidChangeTimer:", userInfo: nil, repeats: true)
    NSRunLoop.currentRunLoop().addTimer(self.minuteDidChangeTimer, forMode: NSDefaultRunLoopMode)

    :
}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)

    self.minuteDidChangeTimer.invalidate()
    self.minuteDidChangeTimer = nil

    :
}

您可能还想更新您的 UI 以响应 UIApplicationSignificantTimeChangeNotification 的重大、意外更改,即“更改为新的一天(午夜)、运营商时间更新以及更改为夏令时或取消夏令时”。

【讨论】:

    【解决方案2】:

    如果您只想在分钟更改时更新,这应该可以解决问题:

    NSDate *date = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];
    [self performSelector:@selector(minuteHasChanged) withObject:nil afterDelay:(60 - dateComponents.minute)];
    

    而且,如果您可以确定只调用此方法一次,那么您可以执行以下操作:

    - (void)minuteHasChanged {
        //do stuff
    
        NSDate *date = [NSDate date];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *dateComponents = [calendar components:NSHourCalendarUnit fromDate:date];
        [self performSelector:@selector(minuteHasChanged) withObject:nil afterDelay:(60 - dateComponents.minute)];
    }
    

    【讨论】:

    • 修改从日期中提取秒组件的解决方案也不起作用。我采用 NSTimer 的解决方案有效,但没有像我预期的那样立即更新标签。
    • 尝试通过调用 [self performSelectoronMainThread:@selector(updateLabel) withObject:nil] 来更新主线程上的标签;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多