Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch statements and instance variable allocation in Objective-C

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;
}
like image 770
Daddy Avatar asked Jan 23 '12 02:01

Daddy


People also ask

What variables are used in a switch statement?

Syntax. The variable used in a switch statement can only be integers, convertable integers (byte, short, char), strings and enums. You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.

What is a switch () statement?

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

Can switch statements use variables?

Variables are not allowed. The default statement is optional and can appear anywhere inside the switch block.

Can switch statements use doubles in C?

The value of the expressions in a switch-case statement must be an ordinal type i.e. integer, char, short, long, etc. Float and double are not allowed. The case statements and the default statement can occur in any order in the switch statement.


1 Answers

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; 
} 
like image 55
Richard J. Ross III Avatar answered Nov 04 '22 05:11

Richard J. Ross III