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

名前の値を設定することはありません。設定する必要があります。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 に答える
1

予測を確認してください。「1」がないか確認してから「1」に設定します。nilたとえば、ユーザーのデフォルトに名前がないかどうかを確認する必要があります。

于 2012-01-06T17:35:53.270 に答える