1

我有许多线程通过 performSeleactoreOnMainThread 方法调用以下函数:

-(void) showAlert: (NSString *)message{
if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop]) {
    NSLog(@"<< perform in main thread>>");
    [self performSelectorOnMainThread:@selector(showAlert:) withObject:message waitUntilDone:NO];
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Info" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}

因为,无论如何,这个方法只会在主线程上调用,我没有得到 EXC_BAD_ACCESS 崩溃的原因:[alert show]

而这种崩溃只是偶尔发生。请帮忙。

4

4 回答 4

2

我猜你忘了添加return;你的代码,这样你的 if 下面的代码也会被执行,无论它是否在主循环中。

一个简单的解决方法可能是:

-(void) showAlert: (NSString *)message{
    if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop]) {
        NSLog(@"<< perform in main thread>>");
        [self performSelectorOnMainThread:@selector(showAlert:) withObject:message waitUntilDone:NO];
        return;
    }
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Info" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
于 2012-12-17T10:41:47.530 回答
0

问题是由于 if 条件是 true 还是 false,alertview 显示方法将起作用。改变你的方法,如:

-(void) showAlert: (NSString *)message
{
 if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop])
 {
    NSLog(@"<< perform in main thread>>");
    [self performSelectorOnMainThread:@selector(showAlert:) withObject:message waitUntilDone:NO];
 }
 else
 {
   UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Info" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
  [alert show];
 }
}
于 2012-12-17T10:41:29.393 回答
0

将 areturn放在 if 块的末尾:

-(void) showAlert: (NSString *)message{
if ([NSRunLoop currentRunLoop] != [NSRunLoop mainRunLoop]) {
    NSLog(@"<< perform in main thread>>");
    [self performSelectorOnMainThread:@selector(showAlert:) withObject:message waitUntilDone:NO];
    return;
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Info" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
}
于 2012-12-17T10:42:49.640 回答
0

替代为什么你不使用这个:

 [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];

代替

 [alert show];
于 2012-12-17T10:58:09.187 回答