【问题标题】:Using a Switch Statement in Obj-C在 Obj-C 中使用 Switch 语句
【发布时间】:2012-04-14 06:47:09
【问题描述】:

下面是一个 Switch / Case 语句,当无法发送电子邮件时显示错误消息。在大多数情况下,一切似乎都是正确的,但是当我将 UIAlertView 放入 Switch 语句时,我在 Xcode 中收到错误:

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

为什么我在case里面放代码会报错?

【问题讨论】:

标签: ios objective-c compiler-errors switch-statement


【解决方案1】:

把它放在括号里:

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

【讨论】:

  • 查看@Phillip Mills 的回答或进行搜索,您会发现很多解释。
【解决方案2】:

问题在于在 switch 的 case 中声明变量。当只执行一些代码时,编译器会因为试图找出作用域而感到不安。如果你在“失败”案例的内容周围加上括号,应该没问题,因为这限制了范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    相关资源
    最近更新 更多