在switch语句中创建新的局部变量似乎有问题.我以为这是我的类头文件,但是甚至在尝试分配一个新的NSObject时收到错误.这是我的语法:
-(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; }
解决方法
在switch语句中,您无法初始化变量而不首先设置范围,因此要进行修改,请执行以下操作:
switch (some_expression) { case case_1: { // notice the brackets id some_obj = [MyObj new]; break; } default: break; }