【问题标题】:How can I use NSBundle in Switch Case of Objective-C如何在 Objective-C 的 Switch Case 中使用 NSBundle
【发布时间】:2013-06-23 15:44:25
【问题描述】:

我输入了以下内容,但显示了一些错误,这是 case 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;
    }
}

【问题讨论】:

    标签: objective-c switch-statement


    【解决方案1】:

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

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

    另外,不要在NSBundle 上使用alloc init。您要么想要获得mainBundle(如上所述),要么专门在您的应用中获得一些其他捆绑包。

    【讨论】:

      【解决方案2】:

      case 块的第一行有一个变量声明。用大括号括起来:

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

      this SO question

      【讨论】:

        【解决方案3】:
        NSBundle *bundle = [NSBundle mainBundle];
        

        是正确的方法。

        【讨论】:

          猜你喜欢
          • 2020-05-08
          • 1970-01-01
          • 2016-09-26
          • 1970-01-01
          • 2012-07-13
          • 1970-01-01
          • 2012-06-29
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多