Objective-c formatting style causes an error in a switch-case
I'm getting an error in my switch statement with some multi-line Objective-c code:
- (void)mailComposeController:(MFMailComposeViewController*)controller
didFinishWithResult:(MFMailComposeResult)result
error:(NSError*)error
{
// Notifies users about errors开发者_运维百科 associated with the interface
switch (result)
{
case MFMailComposeResultCancelled:
break;
case MFMailComposeResultFailed:
// NSLog(@"Mail Failed");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Error", @"Error")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"OK")
otherButtonTitles:nil];
[alert show];
[alert release];
break;
default:
break;
}
}
If I uncomment the line with the NSLog
, it works fine. What's causing this error? Is there any way to use this kind of formatting?
You should not declare a variable in a switch
case
unless you introduce a scope.
case MFMailComposeResultFailed: { // <--
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Error", @"Error")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"OK")
otherButtonTitles:nil];
[alert show];
[alert release];
break;
} // <--
The actual error is because in the C standard (§6.8.1), a label can only be followed by a statement (NSLog(@"Mail Failed")
), not a declaration (UIAlertView* alert = ...
).
The issues is with how switch is defined. You can't have a variable declaration on the line following the case. You can fix it by wrapping the entire case in a new scope
case MFMailComposeResultFailed:
{
// NSLog(@"Mail Failed");
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(@"Error", @"Error")
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"OK", @"OK")
otherButtonTitles:nil];
[alert show];
[alert release];
break;
}
精彩评论