I am trying to set an NSNumber as a float value that has been loaded using NSUserDefaults but i'm getting an error. I can't understand why...?
Here's my code:
[settingsData.sensitivitySettingValue floatValue] = [[NSUserDefaults standardUserDefaults] floatForKey:@"sensitivityKey"];
It works if I use a float on its own (ie float myFloat = [[NSUserDefaults standardUserDefaults] floatForKey:@"sensitivityKey"]
, but I want the value available across all view controllers so I have defined it in a model class as an NSNumber.
So, please would anyone be able to advise me on why that statement wont work?
That looks like you're trying to assign a variable to a getter method, judging by your syntax. What does floatValue do? Return a value or assign one?
taking settingsData as an object of your datamodel class where sensitivitySettingValue is a variable declared as NSNumber using something as
[settingsData.sensitivitySettingValue floatValue]
actually fetches its value rather than setting a float value to it . You can either use the dot notation such as settingsData.sensitivitySettingValue = [NSNumber numberWithFloat:[[NSUserDefaults standardUserDefaults] floatForKey:@"sensitivityKey"]];
or something as
[settingsData setSensitivitySettingValue:[NSNumber numberWithFloat:[[NSUserDefaults standardUserDefaults] floatForKey:@"sensitivityKey"]]];
Hope it helps
You can try
+ (NSNumber *)numberWithFloat:(float)value;
method to assign the value. Here is the Docs .
[settingsData.sensitivitySettingValue setFloatValue:[[NSUserDefaults standardUserDefaults] floatForKey:@"sensitivityKey"]];
确保settingsData.sensitivitySettingValue
支持setFloatValue
方法。
If you want to create NSNumber from float:
float myFloat = [[NSUserDefaults standardUserDefaults] floatForKey:@"sensitivityKey"];
NSNumber *number = [NSNumber numberWithFloat:myFloat];
// settingsData.sensitivitySettingValue = number; - not sure in type of properties
NSUserDefaults also responds to objectForKey
method, you can save/load NSNumber without casting
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.