简体   繁体   中英

How to store a float in NSUserDefaults

I want to store a float value into NSUserDefaults .

I also need to check that the float value exists..if not I need to assign some value in it.

and retrieve it...for the above I have the below code but it gives me an error.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if ([defaults boolForKey:@"HANDWRITING_SIZE_SLIDER"] == YES) {
  self.sizeSlider.value = 10.0;
} else {
  self.sizeSlider.value = [[NSUserDefaults standardUserDefaults] floatForKey:@"HANDWRITING_SIZE_SLIDER"]];      
}

Thanks for any help

Use the NSNumber class for this and store it via the setObject:forKey: method so you can check if it exists.

I'd also suggest the usage of constants as keys:

#define HANDWRITING_SIZE_SLIDER @"HSS"

Your code should be along these lines:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

if ([defaults objectForKey:HANDWRITING_SIZE_SLIDER] == nil) {
  //doesn't exist in NSUserDefaults, set to default value...
  self.sizeSlider.value = 10.0;
} else {
  self.sizeSlider.value = [[defaults objectForKey:HANDWRITING_SIZE_SLIDER] floatValue];
}

Somewhere else in your app, you'd set the value in NSUserDefaults like this:

float sizeSliderValue = ...
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sizeSliderValue] forKey:HANDWRITING_SIZE_SLIDER];

Try this code:

-(IBAction)sliderAction:(id)sender
{
    float sliderValue = [sender floatValue];
    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithFloat:sliderValue] forKey:@"keySliderValue"];

    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"keySliderValue"]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM