将NSUserDefaults与UISegmentedControl一起使用

时间:2015-12-15 15:31:55

标签: ios nsuserdefaults uisegmentedcontrol

这是我在viewDidLoad中编写的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    self.MisureSegmentedControl.selectedSegmentIndex = ([[standardDefaults stringForKey:@"myKey"] isEqualToString:@"Cm"]) ? (1) : (0);
}

这是UISegmentedControl的行动:

- (IBAction)MisureAction:(UISegmentedControl *)sender
{
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    if (sender.selectedSegmentIndex == 0)
    {
        [standardDefaults setObject:@"Cm" forKey:@"myKey"];
    }
    else if (sender.selectedSegmentIndex == 1)
    {
        [standardDefaults setObject:@"Inches" forKey:@"myKey"];
    }
    [standardDefaults synchronize];
}

它不起作用,出了什么问题?

2 个答案:

答案 0 :(得分:1)

我建议保存索引而不是任何字符串值。

在AppDelegate / applicationDidFinishLaunching中注册键/值对以获得可靠的默认值

NSDictionary *defaultValues = @{@"segmentedIndex":  @0};
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultValues];

默认索引为0,将其更改为您喜欢的值。

viewDidLoad中读取值

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    self.MisureSegmentedControl.selectedSegmentIndex = [standardDefaults integerForKey:@"segmentedIndex"];
}

MisureAction保存值

- (IBAction)MisureAction:(UISegmentedControl *)sender
{
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    [standardDefaults setInteger:sender.selectedSegmentIndex forKey:@"segmentedIndex"];
    [standardDefaults synchronize];
}

segmentedIndex是一个任意键。使用你想要的任何东西,但它必须与所有方法相同。

答案 1 :(得分:0)

尝试使用此代码,它会起作用。代码中存在逻辑错误。

- (IBAction)MisureAction:(UISegmentedControl *)sender
{
    NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
    if (sender.selectedSegmentIndex == 0)
    {
        [standardDefaults setObject:@"Inches" forKey:@"myKey"];
    }
    else if (sender.selectedSegmentIndex == 1)
    {
        [standardDefaults setObject:@"Cm" forKey:@"myKey"];
    }
    [standardDefaults synchronize];
}