0

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.

4
  • 1
    You can simply store the NSDate object itself in NSUserDefaults instead of saving it as float.
    – ZeMoon
    Dec 16, 2014 at 12:21
  • You should have to store Double value instead float! Dec 16, 2014 at 12:29
  • with double value the result is the same
    – amurcia
    Dec 16, 2014 at 14:07
  • Thak you @ZeMoon thats the solution
    – amurcia
    Dec 16, 2014 at 14:14

2 Answers 2

2

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 :)

2
  • There is no setDouble method associated with NSUserDefaults
    – ZeMoon
    Dec 16, 2014 at 12:26
  • 1
    @ZeMoon you should check please. Dec 16, 2014 at 12:27
0

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

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.