我有很多线程通过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崩溃的原因: [提示显示]
这种崩溃有时只会发生。请帮忙。
答案 0 :(得分: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];
}
答案 1 :(得分: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];
}
}
答案 2 :(得分:0)
将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];
}
答案 3 :(得分:0)
替代方案为什么不使用它:
[alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
而不是
[alert show];