博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
多线程中UIAlertView无法消失的问题
阅读量:4697 次
发布时间:2019-06-09

本文共 1927 字,大约阅读时间需要 6 分钟。

场景是这样的,点击按钮,开辟新线程,弹出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总会消失。

转载于:https://www.cnblogs.com/Apologize/p/4680535.html

你可能感兴趣的文章
T-SQL中的indexof函数
查看>>
javascript基础之数组(Array)对象
查看>>
mysql DML DDL DCL
查看>>
RAMPS1.4 3d打印控制板接线与测试1
查看>>
python with语句中的变量有作用域吗?
查看>>
24@Servlet_day03
查看>>
初级ant的学习
查看>>
memcached 细究(三)
查看>>
RSA System.Security.Cryptography.CryptographicException
查看>>
webservice整合spring cxf
查看>>
[解题报告] 100 - The 3n + 1 problem
查看>>
Entity Framework 学习高级篇1—改善EF代码的方法(上)
查看>>
Mybatis逆向工程配置文件详细介绍(转)
查看>>
String类的深入学习与理解
查看>>
不把DB放进容器的理由
查看>>
OnePage收集
查看>>
Java parseInt()方法
查看>>
yahoo的30条优化规则
查看>>
[CCF2015.09]题解
查看>>
[NYIST15]括号匹配(二)(区间dp)
查看>>