2012-12-17 48 views
1

我有許多線程調用由performSeleactoreOnMainThread方法如下功能:EXC_BAD_ACCESS只是偶爾上顯示警報視圖

-(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]

而這次崩潰有時只是有時。請幫忙。

+1

提供崩潰日誌 –

回答

2

我想你忘了在你的代碼添加return;使你的代碼下面如果還執行不管是在主迴路與否。

一個簡單的解決方法可能是:

-(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]; 
} 
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]; 
} 
} 
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]; 
} 
0

另類爲什麼不u使用此:

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

而不是

[alert show];