简体   繁体   中英

`NSUserDefaults` not saving float properly

I am building an application in which I want to save some user data by using NSUserDefaults , and it is a property of one of my controllers as following:

  @property (nonatomic, strong) NSUserDefaults *userPreference;
  @synthesize userPreference = _userPreference;

And I am trying to save something called a scale that should be a float, so I do something like this in the getter to put in some default values of scale in case user did not enter one:

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

  if (![_userPreference floatForKey:@"scale"]) { 
      // if user has not entered this info yet
      // also 0 is not a valid value so I can do this
      [_userPreference setFloat:100.0 forKey:@"scale"]; // let default scale be 100.0
      [_userPreference synchronize];
  }

However, when I later on query this, no matter what I set in the default value, the following command:

  [self.userPreference floatForKey:@"scale"];

always return 1 . I am not sure what is happening. Am I not creating the NSUserDefaults correctly?

Thank you in advance!

Store using

   [_userPreference setObject:[NSNumber numberWithFloat:100.0] forKey:@"Scale"];
   [_userPreference synchronize];

and retrieve it using

   float value = [[_userPreference objectForKey:@"Scale"] floatValue];

if you want to use NSUserDefaults, do not create any variables or @propertys. Just use

[[NSUserDefaults standardUserDefaults] setFloat:forKey:]
[[NSUserDefaults standardUserDefaults] synchronize];

to save your data and

[[NSUserDefaults standardUserDefaults] floatForKey:]

for fetching data.

Have you tried this to set the float value:

[_userPreference setObject:[NSNumber numberWithFloat:100.0f] forKey@"scale"];

and the following to retrieve:

CGFloat scale = [[_userPreference objectForKey@"scale"] floatValue];

Change your if condition to this:

if ([_userPreference floatForKey:@"scale"] == 0.0f ) {

NSUserDefaults will always return 0.0f if no value is set for the key. Since you are saying that "also 0 is not a valid", you can safely use this approach

try this

 -(void) saveFloatToUserDefaults:(float)x forKey:(NSString *)key {
     NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setFloat:x forKey:key];
     [userDefaults synchronize];
 }

 -(float) retriveFromUserDefaultsForKey:(NSString *)key {
     NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
     return [userDefaults floatForKey:key];
 }

 [self saveFloatToUserDefaults:6.55 forKey:@"myFloat"];
 float x = [self retriveFromUserDefaultsForKey:@"myFloat"];

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