How to store an retrieve float from NSUserDefaults

你离开我真会死。 提交于 2019-12-04 11:30:58

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.

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"];
[[NSUserDefaults standardUserDefaults]setObject:[NSNumber numberWithFloat:3] forKey:@"key"];

Try this:

  1. For Storing

-(void)sliderAction:(id)sender

{
   [[NSUserDefaults standardUserDefaults] setFloat:fontSlider.value forKey:@"keyFontSize"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

2.For retriving

-(void)retrive
{
   NSLog(@"%f",[storedata floatForKey:@"keyFontSize"]);
}

NSUserDefaults special cases floats as well as a few other native "C" types.

[[NSUserDefaults standardUserDefaults] setFloat:3 forKey:@"key"];

float value = [[NSUserDefaults standardUserDefaults] floatForKey:@"key"];
NSLog(@"value: %.0f", value);

NSLog output:
value: 3

NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
if (pref) {
   [[NSUserDefaults standardUserDefaults] setFloat:3 forKey:@"key"];

   //for accessing
   float value = [pref floatForKey:@"key"]; //if key does not exist, value will be zero
}

Well, no one seems to have explicitly resolved the issue the OP had.
The OP had declared NSUserDefaults in the .h file and was just trying to access it in the .m file without actually alloc'ing the pref instance.
For the sake of the beginner programmer, this means in .h declare the instance:
NSUserDefaults * pref;

and in your .m method, put this before trying to access it:

pref = [NSUserDefaults standardUserDefaults];

It seems obvious to some, but can catch you out every now and then. You will ideally put this somewhere like viewDidLoad, but if you're accessing methods in that class via something like a shared instance, then in the methods you might benefit from putting

if(!pref){ 
pref = [NSUserDefaults standardUserDefaults];
}

before you need to access it, just to make sure it's been allocated memory.
Hope this helps somebody!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!