Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 443
nevan king Avatar asked Jul 09 '10 13:07

nevan king


2 Answers

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 = ...).

like image 95
kennytm Avatar answered Nov 07 '22 05:11

kennytm


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;
    }
like image 25
Joshua Weinberg Avatar answered Nov 07 '22 05:11

Joshua Weinberg