I'm having trouble storing and retrieving a float in NSUserDefauts. I store the value, but when I retrieve it, it returns 0.
here's what I tried and didn't work:
[pref setFloat:3.0f forKey:@"key"];
float value = [pref floatForKey:@"key"]; //value=0
[pref setFloat:3 forKey:@"key"];
float value = [pref floatForKey:@"key"];//value=0
[pref setObject:[NSNumber numberWithFloat:3] forKey:@"key"];
float value = [[pref objectForKey:@"key"]floatValue];//value=0
[pref setObject:[NSNumber numberWithFloat:3.0f] forKey:@"key"];
float value = [[pref objectForKey:@"key"]floatValue];//value=0
What am I doing wrong here? I've tried these 4 pieces of code but they all return zero when retrieving the float from NSUserDefaults.
Any help is appreciated. Thanks!
Save
-(void) saveFloatToUserDefaults:(float)x forKey:(NSString *)key {
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setFloat:x forKey:key];
[userDefaults synchronize];
}
Load
-(float) loadFloatFromUserDefaultsForKey:(NSString *)key {
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
return [userDefaults floatForKey:key];
}
How-To
[self saveFloatToUserDefaults:5.241 forKey:@"myFloat"];
float x = [self loadFloatFromUserDefaultsForKey:@"myFloat"];
The first example in your code is fine, assuming that this line:
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
Appears before it. As I suggested in my comment, the behaviour you are seeing suggests that pref
is nil.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With