【问题标题】:Objective-c formatting style causes an error in a switch-caseObjective-c 格式化样式导致 switch-case 错误
【发布时间】:2011-03-13 20:54:27
【问题描述】:

我在我的 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;
    }
}

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

【问题讨论】:

    标签: objective-c formatting switch-statement


    【解决方案1】:

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

        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;
        } // <--
    

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

    【讨论】:

    • 感谢您的回答。与格式无关,但与声明无关。
    【解决方案2】:

    问题在于如何定义 switch。您不能在 case 后面的行上声明变量。您可以通过将整个案例包装在新范围内来修复它

        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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-08
      • 2019-03-27
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      相关资源
      最近更新 更多