load/save settings in iOS

2019-03-08 04:25发布

问题:

I have the following two procedures defined in my AppDelegate. saveSettings and loadSettings. I am calling my loadSettings procedure in the AppDidFinishLaunching method, and I am calling the saveSettings procedure in my settings view, once the save button is clicked.

Both methods seem to be called at the right time, the right number of times (once), and using the correct data. my settings object gets the right data, but the data does not seem to be actually saving. When I run the load code, my resulting variables are coming back empty (not nil).

I tried putting the same loading code in a different view and it works fine, but for some reason, I am not getting results in my 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"];   
}

回答1:

Doh.

In saveSettings, I was missing my [prefs synchronize];



回答2:

to make it sample:

//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"]