标签:
场景是这样的,点击按钮,开辟新线程,弹出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总会消失。
标签:
原文地址:http://www.cnblogs.com/Apologize/p/4680535.html