I have a piece of code that, when a row in a table view is selected, will display an alert and wait until that alert is dismissed. 虽然它在装有 iOS 5 和 6 的 iPad 上运行良好,但在 iOS 7 上它在尝试解除警报时卡住了。
为了说明这个问题,我创建了一个简单的主从应用程序并创建了一个简单的 MyAlert 类,它扩展了 UIAlertView 并符合 UIAlertViewDelegate:
@interface MyAlert : NSObject <UIAlertViewDelegate>
{
volatile BOOL completed;
UIAlertView * alert;
}
- (void) showAndWaitUntilDone:(NSString*)message;
@结尾
我的警报.m:
@implementation MyAlert
- (void) showAndWaitUntilDone:(NSString*)message
{
alert = [[UIAlertView alloc] initWithTitle:@"Alert"
message:message
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Other", nil];
if (alert)
{
alert.delegate = self;
[self showAndWaitUnitlDone];
}
}
- (void) showAndWaitUnitlDone
{
completed = NO;
[alert show];
while (!completed)
{
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate distantFuture]];
}
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
completed = YES;
}
@end
然后我在我的 ViewController 中显示警报,如下所示:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[MyAlert showAndWaitUntilDone:@"test msg"];
}
效果:
如前所述,这在 iOS 5 和 6 上运行良好。
如果我不阻塞主线程,一切似乎都可以正常工作,但是,如果我从 UIButton 回调运行此代码,它就像一个魅力。