多个UIAlertViews的错误/错误

时间:2014-07-30 12:12:07

标签: ios objective-c debugging

我在使用UIAlertViews时遇到了一个非常奇怪的错误。把头发拉过来,请帮帮我!

按'"创建!&#34>时发生错误。在alert1 alert和checkUsernameExists中返回true,然后按" K。"在alert3。

代码

-(void) newProfile:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"New Profile"
                                                    message:nil
                                                   delegate:self
                                          cancelButtonTitle:@"Create!"
                                          otherButtonTitles:nil];

    alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;

    UITextField *username = [alert textFieldAtIndex:0];
    username.keyboardType = UIKeyboardTypeDefault;
    username.placeholder = @"Desired Username";

    UITextField *password = [alert textFieldAtIndex:1];
    password.keyboardType = UIKeyboardTypeDefault;
    password.placeholder = @"Desired Password";

    [alert1 show];
}
- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *title = [alert title];
    UITextField *username = [alert textFieldAtIndex:0];
    UITextField *passwrod = [alert textFieldAtIndex:1];

    if ([title isEqualToString:@"New Profile"]) {
        if ([self checkUsernameExists:username.text] == false) {
            // Create new account
        }
        else {
            [self errorPop:@"New Profile"];
        }
    }
}
-(void) errorPop:(NSString*)who {
    if ([who isEqualToString:@"New Profile"]) {
        UIAlertView *alert3 = [[UIAlertView alloc] initWithTitle:@"OH NOOOOO"
                                                        message:@"Username is already taken please try another one."
                                                       delegate:self
                                              cancelButtonTitle:@"K."
                                              otherButtonTitles:nil];

        [alert3 show];
    }
}

日志

  

2014-07-30 19:57:49.594 App [6532:a0b] * 终止应用程序   未捕获的异常' NSInvalidArgumentException',原因:   ' textFieldIndex(0)超出了文本数组的范围   字段'

2 个答案:

答案 0 :(得分:3)

第一个警报视图不包含文本字段,因此当您在-clickedButtonAtIndex:中请求第一个或第二个文本字段时,会出现超出范围的异常。

您应该区分哪个警报视图接收回调。尝试在创建时将警报视图存储在属性中,然后在尝试访问文本字段之前在回调中检查其身份。

答案 1 :(得分:1)

只需将alert3的委托设置为nil,这样它就不会进入方法“ - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex”。

实际上,alert3不包含tetxfield,你也为此警报设置了委托,所以它会委托他们试图获取UItextField的方法,但是他们没有这就是它崩溃的原因。