我有一个正在等待连接的应用程序。在应用程序正在等待时,我需要向用户显示AlertView,该用户应在编程后或用户单击AlertView的取消按钮后解散。当主线程在IOS中被阻塞时,UIAlertView在线程中关闭
主线程正在等待客户端连接,其中正如我创建的另一个线程中那样,并显示正在更新对话框上的时间的AlertView。该线程有一个NSRunLoop,用于更新AlertView上的文本。
一切工作正常,但AlertView没有收到触摸事件,甚至没有得到程序化解雇。任何人都可以点亮我在这里可能会做错的事。
以下是示例代码。
funcA() {
[NSThread detachNewThreadSelector:@selector(createDialog) toTarget:self withObject:nil];
[NSThread detachNewThreadSelector:@selector(updateDialog) toTarget:self withObject:nil];
..
..
BlockingWait();
..
..
}
- (void) createDialog {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
alert = [[UIAlertView alloc] initWithTitle:@"Wait" message:@"\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
...
label = [[UILabel alloc] initWithFrame:CGRectMake(30.0f, 20.0f, 225.0f, 90.f)];
[alert show];
[alert release];
[pool drain];
}
- (void) upDateDialog {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSRunLoop *loop = [NSRunLoop currentRunLoop];
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateText) userInfo:nil repeats:YES];
[loop run];
[pool drain];
}
- (void) updateText {
label.text = " Wait for" + n + "secs";
n--;
if (n == 0)
[alert dismissWithClickedButtonIndex:0 animated:YES]; // Doesn't work
}
- (void) alertView: (UIAlertView *) alert clickedButtonAtIndex:(NSInteger) buttonIndex {
// Never Gets called
NSLog(@"Alert is dissmissed with button index %d", buttonIndex);
if (buttonIndex == 0) {
[timer invalidate];
}
}
我知道更好的架构是在主线程中有UI,但我必须为此做很多设计更改。是否可以在辅助线程中听触摸事件? – Rajat 2012-01-17 13:25:14
不可以。UIKit不是线程安全的,只能在主线程以外的线程上运行。你无法解决这个事实。即使你得到某种“有用的东西”,你也将面临显着的竞争条件,这些竞争条件在每个平台和操作系统版本上都可能不同(并且UIKit争用条件*在操作系统版本之间做了改变)。 – 2012-01-17 15:23:27