Ios 循环第一次只运行一次';这叫做无限次

Ios 循环第一次只运行一次';这叫做无限次,ios,objective-c,loops,Ios,Objective C,Loops,我创建了一个循环,它在等待用户在代码继续之前填写警报框时运行。我在其他地方也使用同样的循环,而且效果很好 然而,在这里,它只在第一次调用时循环一次,随后创建另一个警报并再次被调用 第二次运行,直到用户完成其应输入的详细信息 //Method waiting for users credentials - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthentica

我创建了一个循环,它在等待用户在代码继续之前填写警报框时运行。我在其他地方也使用同样的循环,而且效果很好

然而,在这里,它只在第一次调用时循环一次,随后创建另一个警报并再次被调用

第二次运行,直到用户完成其应输入的详细信息

//Method waiting for users credentials
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
    NSLog(@"got auth challange");
    _didChallenge = YES;

    // Ask user for their credentials
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Please enter username and password:" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
    [alertView setTag:1];
    alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    [alertView show];

    [self performSelectorOnMainThread:@selector(WaitForCredentialDialog) withObject:nil waitUntilDone:YES];

    //... Code to deal with credentials is here.
}

//Here dialogResult is a variable which will make while loop run until its value is -1 and reset its value to 1 or 0 when AlertView's Button is clicked
- (void) WaitForCredentialDialog{
    NSDate* LoopUntil;
    LoopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
    while ((dialogResult==-1) && ([[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:LoopUntil]))
    {
        LoopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
    }
}

你不应该为此使用循环!使用
UITextFieldDelegate
获取有关用户键入内容的事件

例子 要检测文本字段中的更改,请使用:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
UIAlertViewDelegate

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
此方法在首次显示警报视图时调用,也在用户每次在其中一个文本字段中键入字符时调用,这使得在接受用户值之前执行基本输入验证非常容易

资料来源:


您正在使用100%的CPU来等待凭证输入?哎哟,我能提供的唯一建议是,这种方法完全错了。您应该使用
UIAlertView
的委托,在用户完成其凭据输入(或决定不输入)且未将运行循环置于等待状态时获得通知。当我之前尝试等待用户输入时,将在
[alertView show]
之后发生什么,在按下OK按钮之前,代码将继续进入if else子句。这是因为UIAlertView不会阻止运行循环(也不应该阻止)。一旦用户发出完成输入的信号,您就应该在委托调用中处理凭据。您还可以找到许多基于块的
UIAlertView
类别,但您应该先了解委托模式。好的,我已经将其更改为使用委托方法。但是,
diReceiveAuthenticationChallenge
仍被多次调用。