【问题标题】:iOS: Access app-info.plist variables in codeiOS:在代码中访问 app-info.plist 变量
【发布时间】:2012-03-20 18:23:10
【问题描述】:

我正在开发一个通用应用程序,并且想在我的代码中访问存储在 app-info.plist 文件中的值。

原因:我使用以下方法从情节提要动态实例化 UIViewController:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPhone" bundle:nil];
self = [storyboard instantiateViewControllerWithIdentifier:@"ExampleViewController"];

现在,上面的故事板名称@“MainStoryboard_iPhone”很丑。

我想做这样的事情:

UIStoryboard* storyboard = [UIStoryboard storyboardWithName:appInfo.mainStoryboardBaseNamePhone bundle:nil];
self = [storyboard instantiateViewControllerWithIdentifier:@"ExampleViewController"];

其中 appInfo 可能是 app-info.plist 中所有值的 NSDictionary

【问题讨论】:

    标签: iphone objective-c ios ipad info.plist


    【解决方案1】:

    Swift 4+ 语法 Damo's solution

    Bundle.main.object(forInfoDictionaryKey: "KEY_NAME")
    

    例子

    let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
    

    【讨论】:

    • 对于像我这样的初学者,Bundle 需要 import SystemConfiguration
    【解决方案2】:

    你也可以在 NSBundle 上使用 infoDictionary 方法:

    NSDictionary *infoPlistDict = [[NSBundle mainBundle] infoDictionary];
    NSString *version = infoPlistDict[@"CFBundleVersion"];
    

    【讨论】:

      【解决方案3】:
      NSString *path = [[NSBundle mainBundle] pathForResource: @"YOURPLISTNAME" ofType: @"plist"]; 
      NSMutableDictionary *dictplist =[[NSMutableDictionary alloc] initWithContentsOfFile:path];
      

      【讨论】:

      • 也可以使用NSDictionary:NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
      【解决方案4】:

      你可以很容易地访问 info.plist:

      获取故事板的名称:

      NSString *storyboard  = [[NSBundle mainBundle].infoDictionary objectForKey:@"UIMainStoryboardFile"];
      

      不确定它是否会检测到它是否在 iPad 中,是否应该使用 UIMainStoryboardFile~ipad 设置的密钥。

      【讨论】:

      • XCode 会根据设备自动使用 iPhone / iPad Storyboard 文件填充键 'UIMainStoryboardFile' :)
      【解决方案5】:

      您项目的 info.plist 中的属性可以通过以下方式直接访问...

      [[NSBundle mainBundle] objectForInfoDictionaryKey:key_name];
      

      例如,要获取版本号,您可以执行以下操作

      NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
      

      有一个问题是版本号现在在 info.plist 中有两个属性 - 但你明白了吗?如果您将 info.plist 视为源代码(右键单击 info.plist - 选择 Open As),那么您将看到您可以使用的所有各种键名。

      【讨论】:

      • 正如@Answerbot 在这篇文章中提到的:stackoverflow.com/a/4059118/1210822 :“CFBundleVersion 已被重新用于构建,版本是 CFBundleShortVersionString”,所以现在要从 plist 中检索版本号,我们需要使用: NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
      • 对于 11.3 它不起作用,因为 NSBundle 已重命名,而新的 Bundle 尚未包含它。你有更新吗?
      • 如果我有一个通过网络分发的企业 iOS 应用程序,我可以在 PLIST 文件中添加键/值对,然后在下载时从应用程序中读取这些值吗?跨度>
      • 我们如何从 AppDelegate.m 更新 CFBundleVersion 的值?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      相关资源
      最近更新 更多