无法将UISwitch设置为存储的NSUserDefaults值

时间:2012-04-11 09:59:34

标签: ios5 uiswitch

我遇到了一个问题,我无法在我的应用中保留UISwitch的状态。我认为问题是我一直在尝试从不同的教程和代码源中获得这么多不同的例子来实现这一点,而我只是没有看到完整的图片。

我已经设置了用户首选项屏幕,相关代码是:

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Trying here to check whether user has run app previously, and if not set default switch value (as defined in IB)
NSString *firstRunValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"testSwitch"];
if (!firstRunValue) {
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"testSwitch"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

return YES;
}

OptionsViewController.h

@property (weak, nonatomic) IBOutlet UISwitch *testSwitch;

OptionsViewController.m

@synthesize testSwitch;

.
.
.

- (void)viewDidLoad
{

[super viewDidLoad];
// Here's the issue - following line does NOT set switch as expected from defaults...
[testSwitch setOn:[[NSUserDefaults standardUserDefaults] boolForKey:@"testSwitch"] animated:NO];

}

.
.
.

- (IBAction)updateTest:(id)sender {
// Action called when switch is clicked to save new state, Log shows 0 or 1 as expected
[[NSUserDefaults standardUserDefaults] setBool:[sender isOn] forKey:@"testSwitch"];
NSLog(@"%@", [[NSUserDefaults standardUserDefaults]valueForKey:@"testSwitch"]);
}

.
.
.

- (IBAction)saveOptions:(id)sender {

// When user clicks "Save" and exits, I synch defaults and dump them, again output is as expected
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%@", [[NSUserDefaults standardUserDefaults] dictionaryRepresentation]);
[self dismissModalViewControllerAnimated:YES];
}

如果有人能让我知道我哪里出错了(用英语而不是Objective-C!)我会很感激,谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

NSString *firstRunValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"firstRun"];

if (!firstRunValue) {
    [[NSUserDefaults standardUserDefaults] setObject: @"BlaBla" forKey:@"firstRun"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"testSwitch"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}