Objective-c格式化样式会导致switch-case出错

nev*_*ing 5 formatting objective-c switch-statement

我的switch语句中出现了一些错误,包含一些多行Objective-c代码:

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我取消注释该行NSLog,它可以正常工作.是什么导致了这个错误?有没有办法使用这种格式?

ken*_*ytm 20

switch case除非引入范围,否则不应在a中声明变量.

    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;
    } // <--
Run Code Online (Sandbox Code Playgroud)

实际错误是因为在C标准(§6.8.1)中,标签后面只能跟一个statement(NSLog(@"Mail Failed")),而不是一个声明(UIAlertView* alert = ...).


Jos*_*erg 9

问题在于如何定义交换机.您不能在案例后面的行上有变量声明.您可以通过将整个案例包装在新范围中来修复它

    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;
    }
Run Code Online (Sandbox Code Playgroud)