繁体   English   中英

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

[英]Saving Value of an UISlider to an Array doesn't work

我实际上试图在plist中保存usersettings,以便我可以从任何地方访问它们。 但是当将UISlider值保存到我的数组时,我始终会发送消息

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

数组看起来像这样:

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

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

为了更好的形式,使用键的内容。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM