为什么我的 switch case 有时需要在 Objective-C 中使用大括号? [英] Why do my switch cases sometime need braces in Objective-C?

查看:51
本文介绍了为什么我的 switch case 有时需要在 Objective-C 中使用大括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时 Xcode 会在 case 后的行上显示错误Expected expression".例如,Xcode 用红色箭头指向 UserContentViewController:

Sometimes Xcode will show an error "Expected expression" on the line after a case. For example, Xcode is pointing to UserContentViewController with a red arrow:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case IndexVideo: 
            UserContentViewController* detailViewController = [[UserContentViewController alloc] initWithUser:self.user];
            [self.navigationController pushViewController:detailViewController animated:YES];
            break;

    }
}

如果我在我的案例周围加上大括号,错误就会消失.首先,我想知道不使用大括号有什么问题.我从来没有在任何其他语言的情况下使用过大括号.其次,为什么 Xcode 只在极少数情况下抱怨我的情况?我不太清楚是什么类型的代码触发了这个错误.

If I put braces around my case, the error is gone. Firstly, I want to know what is the problem with not using braces. I've never used braces in cases in any other language. Secondly, why does Xcode only complain about my cases on rare occasions? I can't quite discern what type of code triggers this error.

推荐答案

基本上,如果你想声明一个变量,你需要添加大括号来定义作用域.

Basically, if you want to declare a variable you need to add the braces to define scope.

ARC 还添加了一些要求(或者更确切地说,更严格的要求)来定义范围(因此在升级旧代码库时,您可能会遇到许多切换案例在受保护范围内"错误需要修复).这是因为 ARC 需要详细了解何时不再引用/不能引用变量,以便正确处理发布.

ARC also adds some requirements (or, rather, stricter requirements) to define scope (so you may get a number of "switch case is in protected scope" errors to fix when upgrading an older codebase). This is because ARC needs to know in detail when a variable isn't / can't be referred to any more so that it can deal with the release correctly.

一切都与向编译器提供有关声明变量范围的足够信息有关.它们是单个案例的一部分,还是多个案例的一部分...

Everything relates back to giving the compiler enough information about the scope of declared variables. Should they be part of a single case, or multiple cases...

这篇关于为什么我的 switch case 有时需要在 Objective-C 中使用大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆