Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store an retrieve float from NSUserDefaults

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!

like image 861
Rafael Moreira Avatar asked Dec 09 '22 01:12

Rafael Moreira


2 Answers

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"];
like image 133
Fernando Cervantes Avatar answered Dec 23 '22 17:12

Fernando Cervantes


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.

like image 40
jrturton Avatar answered Dec 23 '22 16:12

jrturton