我有一個正在等待連接的應用程序。在應用程序正在等待時,我需要向用戶顯示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