[英]NSUserDefaults Passing Variable from one view to the other
I'm trying to pass a variable (probably going to end up being a bool or an int, I just just want to indicate the state of a UISwitch) from one view to another. 我试图将一个视图的变量(可能最终是布尔值或整数,我只想指示UISwitch的状态)传递给一个视图。 I've looked into this and it seems like the best way to do this is NSUserDefaults. 我已经研究过了,看来做到这一点的最好方法是NSUserDefaults。 However every time I try the solutions it seems to crash the app. 但是,每次尝试解决方案时,它似乎都会使应用程序崩溃。 Here's what I've done in my .m file: 这是我在.m文件中所做的事情:
Right-click-dragged the switch to the space in between @interface and @end and created an outlet 右键单击将开关切换到@interface和@end之间的空间,并创建一个插座
@property (weak, nonatomic) IBOutlet UISwitch *officer1;
Right-click-dragged the switch to the space in between @implementation and @end and created an action 右键单击将开关切换到@implementation和@end之间的空间并创建一个动作
- (IBAction)officer1Flipped:(id)sender { [[NSUserDefaults standardUserDefaults] setObject:_officer1 forKey:@"officer1"]; }
But now it crashes whenever I flip that switch. 但是现在,只要我按下该开关,它就会崩溃。 Any idea what I'm doing wrong? 知道我在做什么错吗? Did I forget to include anything? 我忘了包括什么吗?
Instead of saving the whole UISwitch object to the user defaults, save the current on state (BOOL) officer1.isOn 而不是将整个UISwitch对象保存为用户默认值,而是保存当前的on state(BOOL) Officer1.isOn
- (IBAction)officer1Flipped:(id)sender {
[[NSUserDefaults standardUserDefaults] setBool:_officer1.isOn forKey:@"officer1"];
}
Then to read that value, call 然后读取该值,调用
[[NSUserDefaults standardUserDefaults] boolForKey:@"officer1"];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.