Reputation: 314
I have an application which is waiting a connection. While the application is waiting i need to show AlertView to the user which should dismiss after sometime either programmatically or by the user clicking on cancel button of AlertView.
The main thread is waiting for the client to connect, where as in another thread I am creating and showing the AlertView which is updating the time on the dialog. The thread has a has NSRunLoop which updates the text on the AlertView.
Everything works fine except that the AlertView doesn't receives the touch events and even it is not getting dismissed programmatically. Could anyone throw some light on what i might be doing wrong here.
Here is the sample code.
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];
}
}
Upvotes: 0
Views: 1053
Reputation: 299455
Never block the main thread. Not ever. Crate the UIAlertView
asynchronously, hold it in an ivar while you do your other work, and update it as you need to. It is very unlikely that you need any threads or blocking for this at all. Just use NSURLConnection
asynchronously to manage connecting without blocking.
Upvotes: 0
Reputation: 7641
I didn't even read your code, just the headline already shows that you really should work on your architecture. You can try to hack UIKit, but it's designed to be managed by the UI thread only. So move your blocking call in a thread and manage the UIAlertView from the main thread.
Upvotes: 2