JoBu1324 JoBu1324 - 4 months ago 20
Objective-C Question

Can I declare variables inside an Objective-C switch statement?

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...


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?

Answer

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

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