如何使主线程执行等到UIButton Action

时间:2013-10-04 05:35:12

标签: ios objective-c uibutton uialertview nsthread

当用户按下保存时,我有一个UITextField和保存按钮我想弹出警报以确认他是否要保存并等待他的响应。 但不幸的是,似乎警报视图显示不会停止执行或等待用户响应。那我怎么能实现这样的情况呢。

- (IBAction)Savebuttonaction:(UIButton *)sender
{
    UIAlertView *view=[[UIAlertView alloc]initWithTitle:@"message" message:@"Do you want to save" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No", nil];
    [view show];
    if(_isSaveConfirm)
        NSLog(@"Saved");
    else
        NSLog(@"Not Saved");
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0)
    {
        _isSaveConfirm=YES;
    }
    else
    {
        _isSaveConfirm=NO;
    }
}

请注意我无法在alertview委托方法中编写更多步骤。所以请提供替代解决方案。

3 个答案:

答案 0 :(得分:0)

您应该像这样处理用户响应。

- (IBAction)Savebuttonaction:(UIButton *)sender
{
    UIAlertView *view=[[UIAlertView alloc]initWithTitle:@"message" message:@"Do you want to save" delegate:self cancelButtonTitle:@"Yes" otherButtonTitles:@"No", nil];
    [view show];

}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==0)
    {
        // put your logic to save
        NSLog(@"Saved");
    }
    else
    {
        // if you want handle this response
        // put your logic here, otherwise 
        // don't handle it.
        NSLog(@"Not Saved");
    }
}

答案 1 :(得分:0)

你试过BlocksKit吗?

[UIAlertView showAlertViewWithTitle:@"message"
                            message:@"Do you want to save"
                  cancelButtonTitle:@"Yes" otherButtonTitles:@[@"No"] 
                            handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                      if (buttonIndex == 0) {
                          NSLog(@"Saved");
                      } else {
                          NSLog(@"Not Saved");
                      }
                  }];

答案 2 :(得分:0)

你想要这个吗?

- (void)buttonClicked:(id)sender {
    __block BOOL userClicked = NO;
    NSLog(@"Show alert");
    [UIAlertView showWithTitle:@"Synchronized Alert" message:@"" cancelButtonTitle:@"NO" otherButtonTitles:@[@"YES"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
        NSLog(@"Alert clicked");
        userClicked = YES;
    }];
    while (!userClicked) {
        NSDate* timeout = [NSDate dateWithTimeIntervalSinceNow:1.f];
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeout];
    }
    NSLog(@"Do something else");
    // ...
}

上面的代码将记录:

2013-12-09 20:21:07.612 [14728:60b] Show alert
2013-12-09 20:21:14.739 [14728:60b] Alert clicked
2013-12-09 20:21:14.775 [14728:60b] Do something else

如果要使用普通的UIAlertView而不是块样式的UIAlertView,则必须将标志userClicked初始化为成员变量或全局变量,因此您可以在委托方法中重置它。

注意:如果您在一个块中调用方法@sel(buttonClicked:)然后将该块分配给一个调度队列,则上述代码将不起作用,如NSRunLoop runMode does not always process dispatch_async中指出的@rob mayoff,“如果队列正在执行一个块,该队列上没有其他块可以启动。“