我可以在 Objective-C switch 语句中声明变量吗? [英] Can I declare variables inside an Objective-C switch statement?

查看:25
本文介绍了我可以在 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 语句中声明变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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