将UISlider保存到数组的值不起作用

时间:2012-06-07 21:26:05

标签: iphone ios nsarray uislider

实际上我试图将用户设置保存在plist中,以便我可以从任何地方访问它们。但是当将UISlider值保存到我的数组时,我总是发出消息

  

将'float'发送到不兼容类型'id'的参数;

Array看起来像这样:

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

我也尝试过使用MSMutableArray,但这也不行....


另一种解决方案

我用NSUserDefaults尝试了解它并且它有效。

保存设置(应插入viewDidUnload或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];

加载设置(应插入viewDidLoad或ViewDidAppear):

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

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

3 个答案:

答案 0 :(得分:2)

这里的问题是你放入数组的值不是对象。为了做到这一点(虽然我建议使用字典而不是数组),您可能希望为每个字体创建NSNumber个对象。

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

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

要获得更好的表格,请使用密钥的内容。

答案 1 :(得分:0)

确实如此,您无法在数组中存储基元。您最好在NSNumber中将其保存为NSUserDefaults。这就是它的用途。

答案 2 :(得分:0)

您应该使用NSNumber类将值存储到数组中。方法尤其是-numberWithFloat:-numberWithBool

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