Reputation: 4246
I have many threads calling the following function by performSeleactoreOnMainThread method:
-(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];
}
As, in any case, this method will be called only on main thread, I am not getting the reason for EXC_BAD_ACCESS crash on the line: [alert show]
And this crash comes only sometimes. Please help.
Upvotes: 1
Views: 377
Reputation: 38259
Alternative Why don't u use this:
[alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];
instead of
[alert show];
Upvotes: 0
Reputation: 7343
Put a return
at the end of the if block:
-(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];
}
Upvotes: 0
Reputation: 3090
I guess you forgot to add return;
in your code so that your code below the if are also executed no matter it is in main loop or not.
a simple fix may be:
-(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];
}
Upvotes: 2
Reputation: 107231
Issue is due to whether the if condition is true or false the alertview displaying method will work. Change your method like:
-(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];
}
}
Upvotes: 0