在iOS中加载/保存设置

时间:2009-04-23 16:10:55

标签: ios settings nsuserdefaults

我在AppDelegate中定义了以下两个过程。 saveSettings和loadSettings。我在AppDidFinishLaunching方法中调用我的loadSettings过程,并且在单击保存按钮后,我在设置视图中调用saveSettings过程。

两种方法似乎都在正确的时间,正确的次数(一次)调用,并使用正确的数据。我的设置对象获取正确的数据,但数据似乎并没有实际保存。当我运行加载代码时,我生成的变量将返回空(不是零)。

我尝试将相同的加载代码放在不同的视图中并且工作正常,但出于某种原因,我的appDelegate中没有得到结果。

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    [window addSubview:navigationController.view];
    [window makeKeyAndVisible];
    [self loadSettings];
    [self setDefaults];
}

-(void)loadSettings{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    settings.masterLocation = [prefs objectForKey:@"masterLocation"];
    settings.masterPort = [prefs objectForKey:@"masterPort"];
    settings.userName = [prefs objectForKey:@"userName"];
    settings.passWord = [prefs objectForKey:@"passWord"];
    settings.autoLogin=[prefs objectForKey:@"autoLogin"];

    if (settings.autoLogin == nil)
        settings.autoLogin=@"N";
}

-(void)saveSettings:(SharedData *)d{
    settings=d;

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setObject:settings.masterLocation forKey:@"masterLocation"];
    [prefs setObject:settings.masterPort forKey:@"masterPort"];
    [prefs setObject:settings.userName forKey:@"userName"];
    [prefs setObject:settings.passWord forKey:@"passWord"];
    [prefs setObject:settings.autoLogin forKey:@"autoLogin"];   
}

2 个答案:

答案 0 :(得分:29)

卫生署。

在saveSettings中,我错过了[prefs synchronize];

答案 1 :(得分:1)

使其成为样本:

//Writing
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:@"anInt"];
[[NSUserDefaults standardUserDefaults] setDouble:1.2 forKey:@"aDouble"];
[[NSUserDefaults standardUserDefaults] setString:@"aString" forKey:@"aString"];
[[NSUserDefaults standardUserDefaults] synchronize];

//Reading:

int i = [[NSUserDefaults standardUserDefaults] integerForKey:@"anInt"]