0

我遇到了一个问题,我无法在我的应用程序中保留 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;
}

选项视图控制器.h

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

选项视图控制器.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!)我会很感激,谢谢!

4

1 回答 1

0

试试这个:

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

if (!firstRunValue) {
    [[NSUserDefaults standardUserDefaults] setObject: @"BlaBla" forKey:@"firstRun"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"testSwitch"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
于 2012-04-11T10:21:57.340 回答