如何在Objective-C的Switch Case中使用NSBundle

时间:2013-06-23 15:44:26

标签: objective-c switch-statement

我输入了以下内容,但是显示了一些错误,这是在案例0之后的行中预期表达式,并使用未声明的标识符“bundle”。谁能告诉我问题是什么以及如何解决?

非常感谢。

-(IBAction) segmentedControlIndexChanged{
    switch (self.segmentedControl.selectedSegmentIndex) {
        case 0:
            NSBundle *bundle = [[NSBundle alloc ]init];
            NSString *path = [bundle pathForResource:@"HK" ofType:@"plist"];
            placeArray = [[NSArray alloc] initWithContentsOfFile:path];
            break;            
        case 1:
            NSLog(@"case 1");
            break;
        case 2:
            NSLog(@"case 2");
            break;
        case 3:
            NSLog(@"case 3");
            break;
        case 4:
            NSLog(@"case 4");
            break;
        default:
            break;
    }
}

3 个答案:

答案 0 :(得分:4)

您需要一些括号,以便编译器知道要应用的范围:

case 0:
{
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *path = [bundle pathForResource:@"HK" ofType:@"plist"];
    placeArray = [[NSArray alloc] initWithContentsOfFile:path];
    break; 
}

另外,请勿在{{1​​}}上使用alloc init。您要么获得NSBundle(如上所述),要么专门在您的应用中获得其他一些包。

答案 1 :(得分:1)

您在case块的第一行有一个变量声明。将块包裹在大括号中:

case 0:
{
    NSBundle *bundle = [[NSBundle alloc ]init];
    NSString *path = [bundle pathForResource:@"HK" ofType:@"plist"];
    placeArray = [[NSArray alloc] initWithContentsOfFile:path];
    break;
}

请参阅this SO question

答案 2 :(得分:0)

NSBundle *bundle = [NSBundle mainBundle];

是正确的方法。