代码之家  ›  专栏  ›  技术社区  ›  nevan king

OBJECTIVE-C格式样式在开关盒中导致错误

  •  5
  • nevan king  · 技术社区  · 14 年前

    我的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 ,它工作得很好。是什么导致了这个错误?有没有办法使用这种格式?

    2 回复  |  直到 7 年前
        1
  •  20
  •   kennytm    14 年前

    不应在 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
  •  9
  •   Joshua Weinberg    14 年前

    问题在于如何定义开关。在事例后面的行中不能有变量声明。您可以通过将整个案例包装到一个新的范围中来修复它。

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