NSUserDefaults different value when return to background

446 Views Asked by At

I save a value in NSUserDefaults when I put my app in background mode, and then when the app becomes active again the value is different.

I save the value:

- (void)appDidEnterBackground:(NSNotification *)notification {
    //Tiempo inicial de inactividad

    NSUserDefaults *dispositivo = [NSUserDefaults standardUserDefaults];
    NSTimeInterval timestamp = ([[NSDate date]  timeIntervalSince1970] * 1000);

    [dispositivo setFloat:timestamp forKey:@"StartBackground"];

    NSLog(@"Start background: %f", timestamp);

    [[NSUserDefaults standardUserDefaults] synchronize];
}

Log: Start background: 1418731653366.276123

I want to recover the value:

- (void)appDidBecomeActive:(NSNotification *)notification {

    NSUserDefaults *dispositivo = [NSUserDefaults standardUserDefaults];
    NSTimeInterval startDate = [dispositivo floatForKey:@"StartBackground"];
    NSLog(@"Start date: %f", startDate);
}

Log: Start date: 1418731716608.000000

This is the only place I use this value. Thank you for advance.

2

There are 2 best solutions below

2
On

There is nothing went wrong because you are using [NSDate date]...it will updating the current time...

2
On

NSTimeInterval is in double press on it and you will get

typedef double NSTimeInterval;

so you should save value in double not in float

[dispositivo setDouble:timestamp forKey:@"StartBackground"];

and to get data

NSTimeInterval startDate = [dispositivo doubleForKey:@"StartBackground"];

its preferable to save NSDate object :)