user198725878
user198725878

Reputation: 6386

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

Upvotes: 3

Views: 2846

Answers (2)

Rajesh Loganathan
Rajesh Loganathan

Reputation: 11217

Try this code:

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

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

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163238

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];

Upvotes: 12

Related Questions