简体   繁体   English

循环仅在第一次调用时运行一次,无限次运行

[英]Loop runs only once first time it's called, infinite second time

I've created a loop that runs while waiting for a user to fill out boxes in an alert before the code moves on. 我创建了一个循环,该循环在代码继续运行之前等待用户填写警报中的框。 I use the same loops elsewhere and it works perfectly. 我在其他地方使用了相同的循环,效果很好。

Here however, it only loops once the first time it's called, subsequently creating another alert and getting called again. 但是,在这里,它仅在第一次调用时循环一次,随后创建另一个警报并再次被调用。

The second time it runs until the user has finished entering their details as it should. 第二次运行,直到用户完成应输入的详细信息为止。

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

You should not use loops for that! 不应该为此使用循环 Use the UITextFieldDelegate to get events about what user typed. 使用UITextFieldDelegate可以获取有关用户键入内容的事件。

Example

To detect changes in the text field use: 要检测文本字段中的更改,请使用:

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

Or UIAlertViewDelegate 's: UIAlertViewDelegate的:

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView

This method is called both when the alert view is first displayed and also each time the user types a character into one of the text fields, making it very easy to perform basic input validation prior to accepting a user's value. 第一次显示警报视图时,以及每次用户在文本字段之一中键入字符时,都会调用此方法,这使得在接受用户的值之前执行基本输入验证非常容易。

Source: 资源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM