6

Below is a Switch / Case statement that displays an error message when an email cannot be sent. For the most part, everything seems right, but when I place a UIAlertView into the Switch Statement I get an error in Xcode:

Xcode error

switch (result) {
    case MFMailComposeResultCancelled:
        NSLog(@"Result: Mail sending canceled");
        break;
    case MFMailComposeResultFailed:
        NSLog(@"Result: Mail sending failed");
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Sending Failed"
                                                          message:@"The email could not be sent."
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];

        [message show];
        break;
    default:
        NSLog(@"Result: Mail not sent");
        break;
}

Why does it generate an error when I place code inside the case?

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
  • look at[enter link description here][1] [1]: http://stackoverflow.com/questions/366073/instantiating-new-object-within-switch-block-why-does-it-fail – TompaLompa Mar 30 '12 at 15:00
  • No, UIAlertView doesn't need an IBAction. – C0D3 Mar 30 '12 at 15:04
  • possible duplicate of [When converting a project to use ARC what does "switch case is in protected scope" mean?](http://stackoverflow.com/questions/7562199/when-converting-a-project-to-use-arc-what-does-switch-case-is-in-protected-scop) – ughoavgfhw Mar 30 '12 at 15:04

2 Answers2

14

Put it in brackets:

case MFMailComposeResultFailed: {
    NSLog(@"Result: Mail sending failed");
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Sending Failed"
                                                      message:@"The email could not be sent."
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];

    [message show];
    break;
  }
bandejapaisa
  • 26,576
  • 13
  • 94
  • 112
12

The problem is declaring variables inside cases of a switch. The compiler is upset about trying to figure out scope when only some of the code is executed. If you put brackets around the contents of the 'fail' case, it should be OK since that restricts the scope.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57