[英]How to save the state of a UISwitch to file
A similar question on stackoverflow yielded a combination of: 关于stackoverflow的类似问题产生了以下组合:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
and 和
BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];
I've been trying to look into NSUserDefaults, but I understand neither what these pieces of code do, or where they should be in my program. 我一直在尝试研究NSUserDefaults,但我既不了解这些代码的用途,也不了解它们在程序中的位置。
Could anyone tell me where they need to go? 谁能告诉我他们要去哪里? Why doesn't the code below work?
为什么下面的代码不起作用?
- (void)viewDidLoad
{
[super viewDidLoad];
BOOL switchState = [[NSUserDefaults standardUserDefaults] boolForKey:@"mySwitchValueKey"];
if (switchState == YES) {
[hard1ON setOn:TRUE];
} else {
[hard1ON setOn:FALSE];
}
}
- (IBAction)switchValueChanged
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
if (hard1ON.on) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"theChange" object:nil];
} else {
[[NSNotificationCenter defaultCenter] postNotificationName:@"theChange2" object:nil];
}
}
These two statements are used to create an instance of NSUserDefaults
and then setting the switchState
in standardUserDefaults
, that is with your app. 这两个语句用于创建一个实例
NSUserDefaults
,然后设置switchState
在standardUserDefaults
,与您的应用程序。
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setBool:switchState forKey:@"mySwitchValueKey"];
switchState
must be declared anywhere above this statement as BOOL switchState
. switchState
必须在此声明与上述任何地方宣布BOOL switchState
。
From this statement BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];
从该语句中
BOOL swichState = [userDefaults boolForKey:@"mySwitchValueKey"];
the boolValue is read back into swichState. boolValue被读回到swichState。
The above code should be in the method that is invoked when you change or flip or move to aother view, assuming switchState is an local property to a class. 假设switchState是类的本地属性,则以上代码应在更改,翻转或移动到另一个视图时调用的方法中。
If it is a global or shared it can be any where, most suitable place would be applicationSholdTerminate:
. 如果它是全局的或共享的,则可以在任何地方,最合适的地方是
applicationSholdTerminate:
For more details check this link , it might give you brief description about NSUserDefaults. 有关更多详细信息,请检查此链接 ,它可能为您提供有关NSUserDefaults的简短描述。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.