views:

210

answers:

2

I am using the following code to save values from a settings view that takes values from a UITextField and stores them with NSUserDefaults. The code below even calls synchronize yet it is not saving the changes. What am I doing wrong here?

- (IBAction)save {
    NSLog(@"save");

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    if (self.usernameTextField.text != nil) {
        NSLog(@"username: %@", self.usernameTextField.text);
        [defaults setObject:kTwitterUsernameKey forKey:self.usernameTextField.text];
    }
    if (self.passwordTextField.text != nil) {
        NSLog(@"password: %@", self.passwordTextField.text);
        [defaults setObject:kTwitterPasswordKey forKey:self.passwordTextField.text];
    }

    [defaults synchronize];

    [self dismissModalViewControllerAnimated:TRUE];
}
+6  A: 

You are setting the key to the username and password, with the username/password string as the value.

So, you'll never be able to retrieve this data (unless you know the username and password already ;) )

if (self.usernameTextField.text != nil) {
    NSLog(@"username: %@", self.usernameTextField.text);
    [defaults setObject:self.usernameTextField.text forKey:kTwitterUsernameKey];
}

Try swapping as shown above.

MarkPowell
Don't forget to call `[defaults synchronize]` after you make changes.
St3fan
He does, so I've only shown a snippet of his code snippet. :)
MarkPowell
A: 

You need to set your kTwitterUsernameKey like below

//Saving kTwitterUsernameKey
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.usernameTextField.text forKey:kTwitterUsernameKey];
//Retrieving kTwitterUsernameKey
NSString *myString = [defaults stringForKey:@"kTwitterUsernameKey"];

The general pattern for NSUserDefaults is like below

    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// retrieve an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
Iggy