zoukankan      html  css  js  c++  java
  • 多线程中UIAlertView无法消失的问题

    场景是这样的,点击按钮,开辟新线程,弹出alertView。然后调用dismissWithClickedButtonIndex让其消失。

     1 /** 定义按钮 */
     2 -(void)setupAllBtns{  
     3     UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     4     btn2.frame = CGRectMake(100, 140, 100, 50);
     5     [btn2 setTitle:@"读取信息" forState:UIControlStateNormal];
     6     [btn2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     7     btn2.backgroundColor = [UIColor brownColor];
     8     [btn2 addTarget:self action:@selector(readSimWithNewThread) forControlEvents:UIControlEventTouchUpInside];
     9     [self.view addSubview:btn2];
    10 }
    11 
    12 -(void)readSimWithNewThread{
    13     NSThread *button3Thread = [[NSThread alloc] initWithTarget:self selector:@selector(readInfo) object:nil];
    14     [button3Thread setName:@"thread-3"];
    15     [button3Thread start];
    16 }
    17 
    18 /** 新线程读取信息 */
    19 -(void)readInfo{
    20     [[NSOperationQueue mainQueue] addOperationWithBlock:^
    21      {
    22          self.mAlertView = [[UIAlertView alloc] initWithTitle:nil message:@"开始读取,请稍候..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    23          [self.mAlertView show];
    24      }];
    25     
    26     char sn[64] = {0};
    27     int ret = [self.sim GetInfo:sn];
    28     
    29     //alert消失的方法
    30     if (self.mAlertView.visible) {
    31         [self.mAlertView dismissWithClickedButtonIndex:0 animated:YES];
    32     }
    33     
    34     NSString *msg = @"";
    35     msg=[NSString stringWithFormat:@"MobileNum=%@",[NSString stringWithUTF8String:sn]];
    36 }

    但有时会出现alert界面一直出现,造成界面卡死。
    原因在于由于用多线程,线程阻塞时,调用alert消失时,alertView还没有绘制出来。当alertView绘制出来时,alert消失的方法已经过时。
    解决方法是在执行alert消失的方法时,让线程暂停一段时间。如0.5s

    [NSThreadsleepForTimeInterval:0.5]; 

    或是用

    [self performSelector:@selector(dimissAlert) withObject:alert afterDelay:2.0];
    //将其添加在[self.mAlertView show]之后
    
    -(void)dimissAlert{
        if (alert.visible) {
            [alert dismissWithClickedButtonIndex:0 animated:YES ];
        }
    }

    这样在固定时间后,alert总会消失。

  • 相关阅读:
    终端创建scrapy项目时报错(转)
    redis的一些命令
    pom.xml中build标签
    spring与mybatis四种整合方法
    linux lsof/netstat查看进程和端口号相关命令:
    ps -ef |grep 输出的具体含义
    java web项目在linux部署、启动,查看系统配置常用的linux命令总结
    linux mysql操作命令大全
    mysql中between...and..的使用,及时间范围的查询
    mysql中if()函数使用
  • 原文地址:https://www.cnblogs.com/Apologize/p/4680535.html
Copyright © 2011-2022 走看看