开发者

NSUserDefaults: Saved Number Always 0, iPhone

I have looked at other answers and the docs. Maybe I am missing something, or maybe I have another issue. I am trying to save a number on exiting the app, and then when the app is loaded I want to check if this value exists and take action accordingly. This is what I have tried:

To save on exiting:

- (void)applicationWillTerminate: (UIApplication *) application
{
 double save = [label.text doubleValue]; // This could be the issue

//double save = 3.5; // This works, it saves the value and loads it fine, so that is not the problem here.

 [[NSUserDefaults standardUserDefaults] setDouble: save forKey: @"savedNumber"];
 [[NSUserDefaults standardUserDefaults] synchronize]; 
}

To check:

- (IBAction)buttonclickSkip{

 double save = [[NSUserDefaults standardUserDefaults] doubleForKey: @"savedNumber"];

 if (save == 0) {

    [self performSelector:@selector(displayAlert) withObject:nil];

    test.enabled = YES;
    test.alpha = 1.0;

    skip.enabled = NO;
    skip.alpha = 0.0;

   }

 else {

 labe开发者_高级运维l.text = [NSString stringWithFormat:@"%.1f %%", save]; 
}

}

The problem is I always get my alert message displayed, the saved value is not put into the label so somehow == 0 is always true. Why would:

double save = [label.text doubleValue];

always equal zero? Before I close the app the number in that label is roughly 0.5% (it varies). If it makes any difference I am testing this on the iPhone simulator.

Many thanks,

Stu


The fact that you can hard-code the value and fetch it back means the problem definitely revolves around your interaction with the label.text and not your use of NSUserDefaults.

Make sure that the label has not already been destroyed at the time you go to fetch its value. As the application is terminating it may have already brought down the view from which you are fetching the value.

Another thing to try would be to get the actual text itself instead of asking the OS to convert the text value into a number first. If you print that out you may get some clue as to what is going on.


Make sure that your applicationWillTerminate: implementation is in your app delegate class.


My guess would be that the text in your label is not a valid double value. From the Apple docs for NSString -doubleValue:

Returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number.

Make sure you are passing it something like @"13.2". The best way to check this is to stick a NSLog call right after you create the variable save.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜