Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Switch Statement in Obj-C

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?

like image 503
Sam Spencer Avatar asked Mar 30 '12 14:03

Sam Spencer


2 Answers

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;
  }
like image 104
bandejapaisa Avatar answered Oct 16 '22 11:10

bandejapaisa


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.

like image 22
Phillip Mills Avatar answered Oct 16 '22 11:10

Phillip Mills