如何使用NSUserDefaults保存按钮状态

时间:2012-05-16 09:17:51

标签: iphone objective-c ios nsuserdefaults

我是iphone的新手。我有一个小小的疑问,就是当我点击该按钮执行以下操作时,我有一个名为Sync off的按钮:

- (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {
    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    } 
    else {
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }
}

由于上面的代码,当我点击按钮时,标题会交替显示。

如何使用NSUserDefaults保存具有不同标题的按钮状态。如果有人知道这一点,请帮助我......

2 个答案:

答案 0 :(得分:4)

您需要定义一个键来保存此按钮示例:

 #define KEYSTATE @"key.syncState"

并在您的函数中:

-  (IBAction)syncOffClickedInRegisterUserScreen:(id)sender {

    // Get User Defaults
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

    if ([syncOnorOff.titleLabel.text isEqualToString:@"Sync off"]) {
        [prefs setBool:NO forKey:KEYSTATE];
        [syncOnorOff setTitle:@"Sync on" forState:UIControlStateNormal];
    } 
    else {
        [prefs setBool:YES forKey:KEYSTATE];
        [syncOnorOff setTitle:@"Sync off" forState:UIControlStateNormal];
    }

    // save 
    [prefs synchronize];
}

然后你可以获得bool(例如viewDidLoad:) 像这样设置按钮:

if ([[NSUserDefaults standardUserDefaults] boolForKey:KEYSTATE]) {
    // Set ON
}
else {
    // Set OFF
}

答案 1 :(得分:0)

UIButton *button;

// get nsuserdefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// save selected state
[defaults setBool:button.selected forKey:@"myButtonState"];

之后,应用程序再次启动后......

// restore the selected state
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
button.selected = [defaults boolForKey:@"myButtonState"];