objc中的时间变化通知(小时和分钟)

时间:2015-05-26 18:11:27

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

最佳做法是在时间变化时获取通知吗?

我使用it('should close the modal on successful save', function () { spyOn(itemSrv, 'save').and.callFake(function () { deferred = q.defer(); deferred.resolve(); return {$promise: deferred.promise}; }); spyOn(modalInst, 'close').and.callThrough(); ItemCtrl.save(); scope.$digest(); expect(modalInst.close).toHaveBeenCalled(); }); 检查每隔0,002秒,如果时间有所改变(小时和分钟,而不是秒和毫秒),以保持我的应用程序中的标签与电话时钟每分钟同步。

我希望有更好的解决方案。

谢谢

2 个答案:

答案 0 :(得分:4)

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

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)];
}

答案 1 :(得分:2)

从下一分钟开始设置定期计时器:

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

    :
}

您可能还想更新您的用户界面以响应UIApplicationSignificantTimeChangeNotification主要的意外更改,即“更改为新的一天(午夜),运营商时间更新以及更改为夏令时或更改夏令时”。