0

在我的 ViewDidLoad 的 .m 文件中,我有以下代码:

 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{

}

正如你所看到的,用户可以在这里保存他的名字,这样他就不必一遍又一遍地输入它。除此之外,他不会再被问到是否输入了它。但是,该应用程序在加载时不显示名称,而是显示数字 1。我想我在这里遗漏了明显的内容。

4

2 回答 2

1

检查您的 if 预测。您检查是否没有“1”,然后将其设置为“1”。也许您应该检查nil用户默认值中是否没有名称。

于 2012-01-06T17:35:53.270 回答
1

您永远不会设置 Name 值,它应该在alertView:clickedButtonAtIndex:

我还建议取消@“1”,并检查 nil(如@Roman 建议的那样)或将 BOOL 存储在另一个默认键中。

...
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];
}

您可以根据自己的逻辑进行调整

于 2012-01-06T18:00:28.080 回答