我的一个视图控制器中有一些元素,我已经为其设置了恢复,以便在视图之间导航时以及程序终止时保存值。所有值都按需保存,但以下的一个例外是每次重新打开视图时恢复为“0”的BOOL。
这是我在视图控制器头中声明变量的地方:
@interface TankViewController : UIViewController <UITextFieldDelegate>
{
BOOL bigTank;
}
以下是我的视图控制器实现文件中的代码。所有其他元素以相同的方式保存并起作用,而这一个保持恢复为NO /“0”:
// Restoration of user fields
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
// tank selector segmented control for equation
[coder encodeBool:bigTank forKey:@"bigTankEquation"];
// these are necessary to set the NSUserDefaults if the user terminates the app without going back to the menu first
// tank size state
[[NSUserDefaults standardUserDefaults] setBool:bigTank forKey:@"bigTankRestore"];
[super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
// tank size state
bigTank = [coder decodeBoolForKey:@"bigTankEquation"];
[super decodeRestorableStateWithCoder:coder];
}
// this will save states when going back and forth between views
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
// tank size state
[[NSUserDefaults standardUserDefaults] setBool:bigTank forKey:@"bigTankRestore"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)viewWillAppear:(BOOL)animated
{
// checks whether or not the view has launched already. If it has not, viewDidLoad handles initialization and NSUserDefaults are updated to change flag to YES. Subsequent loads will restore using NDUserDefaults for view-to-view restore and encode/decode for background/terminate/restart restore
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"TCVHasLaunchedOnce"])
{
// view already launched
[super viewWillAppear:animated];
// tank size state
bigTank = [[NSUserDefaults standardUserDefaults] boolForKey:@"bigTankEquationRestore"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"This is a subsequent launch of the Tank Calculator View");
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"TCVHasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
// This is the first launch ever
NSLog(@"This is the first launch of the Tank View");
}
}
真正疯狂的是我的控制台在返回视图后立即看起来像这样:
2014-02-17 02:38:48.301 myapp[5086:60b] bigTank value = 0
2014-02-17 02:38:48.302 myapp[5086:60b] bigTank current Default = 1
如何将默认值保存为1,但值为0对我来说是不可理解的。任何帮助将不胜感激。谢谢!