简体   繁体   中英

Saving Value of an UISlider to an Array doesn't work

im actual trying to save the usersettings inside a plist so that i can access them from everywhere. But when saving the UISlider value to my Array i always geht the message

Sending 'float' to parameter of incompatible type 'id';

the Array looks like this:

NSArray *value = [[NSArray alloc] initWithObjects: [theGradeSlider value], [theBackgroundSound isOn], [theButtonSound isOn], nil];

i also tried with MSMutableArray but this doesn't work too....


ANOTHER SOLUTION

i tried it know with NSUserDefaults and it worked.

to save the Settings (should be inserted in viewDidUnload or viewDidDiassappear):

NSUserDefaults *settings = [[NSUserDefaults alloc] initWithUser:@"User"];

[settings setFloat:theGradeSlider.value forKey:@"theGradeSlider"];
[settings setBool:theBackgroundSound.on forKey:@"theBackgroundSound"];
[settings setBool:theButtonSound.on forKey:@"theButtonSound"];
[settings synchronize];

to load the Settings (should be inserted in viewDidLoad or ViewDidAppear):

NSUserDefaults *settings = [[NSUserDefaults alloc] initWithUser:@"User"];

theGradeSlider.value = [settings floatForKey:@"theGradeSlider"];
theBackgroundSound.on = [settings boolForKey:@"theBackgroundSound"];
theButtonSound.on = [settings boolForKey:@"theButtonSound"];

The problem here is that the values you are putting into the array are not objects. In order to do this (although I would suggest a dictionary as opposed to an array), you would want to create NSNumber objects for each.

NSNumber *sliderValueObj = [NSNumber numberWithFloat: [theGradeSlader value]];
NSNumber *backgroundSoundObj = [NSNumber numberWithBool: [theBackgroundSound isOn]];
NSNumber *buttonSoundObj = [NSNumber numberWithBool: [theButtonSound isOn]];

NSArray *value = [[NSArray alloc] initWithObjects: sliderValueObj,backgroundSoundObj,buttonSoundObj, nil];

or

NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys: sliderValueObj, @"slider",
                      backgroundSoundObj, @"backgroundSound",
                      buttonSoundObj, @"buttonSound",
                      nil];

For better form, use contents for the keys.

This is true, you cannot store primitives in an array. You're probably better off saving them as NSNumber in the NSUserDefaults . That's what it's for.

You should be using the NSNumber class to store your values to the array. Methods in particular are -numberWithFloat: and -numberWithBool .

NSArray *value = [[NSArray alloc] 
         initWithObjects:[NSNumber numberWithFloat:[theGradeSlider value]], 
                         [NSNumber numberWithBool:[theBackgroundSound isOn]], 
                         [NSNumber numberWithBool:[theButtonSound isOn]], nil];

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