2012-01-16 60 views
0

我有一个正在等待连接的应用程序。在应用程序正在等待时,我需要向用户显示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]; 
    } 
} 

回答

2

我甚至没有读过你的代码,只是标题已经显示你真的应该在你的架构上工作。你可以尝试破解UIKit,但它的设计只能由UI线程管理。所以在一个线程中移动你的阻塞调用,并从主线程管理UIAlertView。

0

千万不要阻塞主线程。永远不会。按照异步方式对UIAlertView进行打包,在做其他工作的同时将其保持在ivar中,并根据需要进行更新。根本不需要任何线程或阻塞。异步使用NSURLConnection来管理连接而不会阻塞。

+0

我知道更好的架构是在主线程中有UI,但我必须为此做很多设计更改。是否可以在辅助线程中听触摸事件? – Rajat 2012-01-17 13:25:14

+0

不可以。UIKit不是线程安全的,只能在主线程以外的线程上运行。你无法解决这个事实。即使你得到某种“有用的东西”,你也将面临显着的竞争条件,这些竞争条件在每个平台和操作系统版本上都可能不同(并且UIKit争用条件*在操作系统版本之间做了改变)。 – 2012-01-17 15:23:27