在两个 NSDate 之间减去 1 分钟

Subtract 1 minute between two NSDate

在我的应用程序中,我有一个 UIProgressView,它显示两个 NSDate 之间经过的时间。一切正常,通过 UIProgressView 的每一分钟每分钟前进 0.1。

两个日期之间的差异是用CGFloat这样计算的

除此之外,我还有一个 UIButton,每次按下按钮时,它应该具有 "decrease the ProgressView 0.1" 的功能 我想花一分钟时间了解我之前创建的两个 NSDate 之间的区别.我做了几次尝试,但我无法做到这一点,因为当我的应用程序关闭然后重新打开时,两个日期之间的时差不会改变......我该怎么做?

我给你看我正在使用的代码

-(void)viewDidLoad {
    [super viewDidLoad];
    [self startDate];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self upgradeEnergyBar];
    [NSTimer scheduledTimerWithTimeInterval: (1 * 60)
                                     target:self
                                   selector:@selector(upgradeEnergyBar)
                                   userInfo:nil
                                    repeats:YES];
}

-(void)startDate {
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    if (! [defaults boolForKey:@"notFirstRun"]) {
        NSDate *date = [NSDate new];
        [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"open"];
        NSLog(@"Ora di apertura : %@", date);
        [defaults setBool:YES forKey:@"notFirstRun"];
    }
}

- (IBAction)sfAction:(id)sender {
    //Decrement CGFLOAT
}

-(void)upgradeEnergyBar {
    self.now = [NSDate new];
    NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"open"];
    NSTimeInterval timeInterval = [self.now timeIntervalSinceDate:lastDate];
    _minutes = timeInterval / 60;

    _energyBar.progress = _minutes * 0.1;
    [self updateLabelEnergyWithProgress:_energyBar.progress];
    _minute.text = [NSString stringWithFormat:@"MINUTES:%ld", (long) _minutes];


    NSLog(@"MINUTES:%ld", (long) _minutes);

    if (_energyBar.progress == 1) NSLog(@"end");
}

你似乎有几个问题,但要回答你的 "how to Subtract a minute" ...

您真正想做的是 向您保存的日期添加一分钟。所以,在 sfAction: 你可以:

- (IBAction)sfAction:(id)sender {

    // get the 'saved' date/time
    NSDate *lastDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"open"];

    // add one minute (60 seconds)
    lastDate = [lastDate dateByAddingTimeInterval:60];

    // get the current date/time
    NSDate *now = [NSDate date];

    // use the earlier date/time (to avoid a date/time in the future)
    NSDate *earlier = [lastDate earlierDate:now];

    // save it back to User Defaults
    [[NSUserDefaults standardUserDefaults] setObject:earlier forKey:@"open"];

}

编辑: 现在包含代码以确保我们不会将保存的 date/time 递增到比当前 date/time 晚的时间。

旁注...

经常read/write 用户默认设置确实不是一个好主意。

您应该 读取 您的应用程序启动时的值(或者当它 returns 进入前台时)并将这些值保存在变量/属性中。

当您的应用程序退出(或发送到后台)时,您可以写入更新的值。