我可以在 Objective-C switch 语句中声明变量吗?

Can I declare variables inside an Objective-C switch statement?(我可以在 Objective-C switch 语句中声明变量吗?)
本文介绍了我可以在 Objective-C switch 语句中声明变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我要瞎了,因为我不知道这段代码中的语法错误在哪里:

I think I'm going blind, because I can't figure out where the syntax error is in this code:

if( cell == nil ) {
    titledCell = [ [ [ TitledCell alloc ] initWithFrame:CGRectZero
        reuseIdentifier:CellIdentifier ] autorelease
    ];

    switch( cellNumber ) {
        case 1:
            NSString *viewDataKey = @"Name";
etc...

当我尝试编译它时,我得到一个 Error: syntax error before '*' token 在最后一行.

When I try to compile it, I'm getting an Error: syntax error before '*' token on the last line.

很抱歉问了这么一个基本问题,但我错过了什么?

Sorry for such a basic question, but what am I missing?

推荐答案

我手头没有合适的 Objective-C 编译器,但只要 C 结构相同即可:

I don't have a suitable Objective-C compiler on hand, but as long as the C constructs are identical:

switch { ... } 为您提供 一个 块级范围,而不是每个 case 一个.在作用域开头以外的任何地方声明变量都是非法的,并且在 switch 内部是特别危险的,因为它的初始化可能会被跳过.

switch { … } gives you one block-level scope, not one for each case. Declaring a variable anywhere other than the beginning of the scope is illegal, and inside a switch is especially dangerous because its initialization may be jumped over.

以下任一方法能否解决问题?

Do either of the following resolve the issue?

NSString *viewDataKey;
switch (cellNumber) {
    case 1:
        viewDataKey = @"Name";
    …
}

switch (cellNumber) {
    case 1: {
        NSString *viewDataKey = @"Name";
        …
    }
    …
}

这篇关于我可以在 Objective-C switch 语句中声明变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to stop UIBarButtonItem text from truncating?(如何阻止UIBarButtonItem文本被截断?)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)
Android IllegalArgumentException: The tag for fragment_XXX is invalid. Received: layout-sw600dp/fragment_XXX_0(Android IlLegalArgumentException:Fragment_XXX的标签无效。收到:Layout-sw600dp/Fragment_XXX_0)
NSURLSessionTaskPriority seems to be ignored?(NSURLSessionTaskPriority似乎被忽略了?)
How to make dataWithEPSInsideRect vector rather than bitmap in vector format?(如何用EPSInside Rect将dataWithEPSInside Rect变成矢量而不是位图的矢量格式?)
HTTPS request using volley(使用 volley 的 HTTPS 请求)