0

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.

Blade
  • 1,435
  • 1
  • 14
  • 22

2 Answers2

1

Check your if prediction. You check if there's not "1" and than set it to "1". maybe you should check if there's nil e.g. no name in user defaults.

Roman Temchenko
  • 1,796
  • 1
  • 13
  • 17
1

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

bshirley
  • 8,217
  • 1
  • 37
  • 43
  • Thanks. I couldnt get it to work with nil so I tried your solution. Only problem is that now the alertview always pops up when the view is loaded. I tried it with another if, but havent got the right one yet. – Blade Jan 06 '12 at 18:35
  • `if ([[NSUserDefaults standardUserDefaults] objectForKey:@"Name"]] == nil)` didn't work? – bshirley Jan 06 '12 at 18:46
  • Thank you very much a thousand times. I did it a wee bit different. :) – Blade Jan 06 '12 at 18:56
  • I would vote your answer up but I dont have enough reputation sorry – Blade Jan 06 '12 at 19:32