问题描述
我想我会盲目,因为我无法弄清楚这段代码中的语法错误在哪里:
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:语法错误,位于'*'标记之前.
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语句中声明变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!