Search code examples
iostableviewalertview

UIAlertView with UITextField - Saving with NSUserDefaults


In the .m file of my ViewDidLoad I have the following code:

 if (![@"1" isEqualToString:[[NSUserDefaults standardUserDefaults] objectForKey:@"Name"]]) {
    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:@"Name"];
    [[NSUserDefaults standardUserDefaults] synchronize];


UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"What is your name?" message:@"\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Send", nil];

UITextField *utextfield = [[UITextField alloc] initWithFrame:CGRectMake (9.0, 60.0, 260.0, 25.0)]; utextfield.placeholder =@"Username";
[utextfield setBackgroundColor:[UIColor whiteColor]];
[alertview addSubview:utextfield];

[alertview show];

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

}

As you can see the user can save his name here so he doesn't have to enter it over and over again. In addition to that he won't get asked again if he entered it. BUT instead of displaying the name when its loaded, the app displays the number 1. I guess I'm missing the obvious here.


Solution

  • You are never setting the Name value, it should be done in alertView:clickedButtonAtIndex:

    I would also suggest doing away with the @"1", and either checking for nil (as @Roman suggests) or storing a BOOL in another defaults key.

    ...
    utextfield.tag = 9876; // some value likely not in use by the internals
    
    
    
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
      if (buttonIndex == alertView.cancelButtonIndex) {
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"Name"];
      } else if (buttonIndex == alertView.firstOtherButtonIndex) {
        UITextField *utextfield = (UITextField *)[alertView viewWithTag:9876];
        [[NSUserDefaults standardUserDefaults] setValue:utextfield.text forKey:@"Name"];
      }
      [[NSUserDefaults standardUserDefaults] synchronize];
    }
    

    you can adjust that as your logic suits you