ios - 循环在第一次被调用时只运行一次,第二次无限次

标签 ios objective-c loops

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

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

它第二次运行,直到用户按应有的方式完成输入他们的详细信息。

//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

当首次显示警报 View 时以及每次用户在其中一个文本字段中键入字符时都会调用此方法,这使得在接受用户值之前执行基本输入验证变得非常容易。

来源:

关于ios - 循环在第一次被调用时只运行一次,第二次无限次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25061522/

相关文章:

ios - HealthKit:收到由 body 事件,背景和终止状态触发的通知(Obj-C,iOS 10.3)

objective-c - 为什么在实现我自己的 KVC setter/getter 方法时会出现未捕获的异常

ios - 当应用程序关闭或终止时,将 textField 中的数据保存到文件中

javascript - 迭代遍历嵌套对象中的所有节点(不使用递归)

javascript - 循环遍历 Javascript 中的函数

ios - Remote Simulator to Windows 选项不存在

ios - nil 合并运算符 '??' 的左侧具有非可选类型 'String' ,因此从不使用右侧

ios - 原因: 'An NSManagedObject of class ' NSManagedObject' must have a valid NSEntityDescription?

objective-c - Swift 中的 MFMailComposeViewController 不会关闭

javascript - jquery 未捕获语法错误 : Illegal break statement