9

I seem to be having a problem creating new local variables inside a switch statement. I thought it was something in my class headers, but was even getting errors trying to allocate a new NSObject. Here's my syntax:

-(NSArray *)charactersFromChapter:(NSInteger)number {
    NSObject *noError = [[NSObject alloc] init];
    //line above does not cause error
    NSArray *characters;
    switch (number) {
        case 1:
            NSObject *obj = [[NSObject alloc] init];
            //error happens in line above (Expected expression)
            characters = [NSArray arrayWithObject:obj];
            break;
        case 2:

            break;
        case 3:

            break;
    }
    return characters;
}
Daddy
  • 9,045
  • 7
  • 69
  • 98
  • 2
    Note, those aren't 'ivars'. An ivar is an instance variable, something you'd declare in the header file. These are simply local variables. It sure would be nice if the C standards committee would allow the style you've attempted. – Graham Perks Jan 23 '12 at 02:50
  • thanks for the clarification, i'll amend the question – Daddy Jan 23 '12 at 02:56
  • 1
    @GrahamPerks: Ivars don't need to be in the header anymore; they can be immediately after the `@implementation` line. – Peter Hosey Jan 23 '12 at 04:06

3 Answers3

32

In a switch statement, you cannot initialize variables without setting a scope first, so to fix it, do something like this:

switch (some_expression) {
   case case_1:
   { // notice the brackets
       id some_obj = [MyObj new];
       break;
   }
   default:
       break; 
} 
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • yep, that fixed it. Thanks for the prompt reply. will accept answer after 10 minutes when it's allowed – Daddy Jan 23 '12 at 02:48
5

You need to either declare "obj" outside of the switch statement, or use braces as follows:

switch (number) {
    case 1: {
        NSObject *obj = [[NSObject alloc] init];
        //error happens in line above (Expected expression)
        characters = [NSArray arrayWithObject:obj];
        break;
    }

See here for more information: Why can't variables be declared in a switch statement?

Community
  • 1
  • 1
iccir
  • 5,078
  • 2
  • 22
  • 34
1

In switch-case you can only use expressions.

You can fix this by using something like this:

case 1:
{
       NSObject *obj = [[NSObject alloc] init];
       characters = [NSArray arrayWithObject:obj];
       break;
}
YuAo
  • 1,427
  • 1
  • 10
  • 17