我正在开发一个通用应用程序,并且想在我的代码中访问存储在 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
您项目的 info.plist 中的属性可通过以下方式直接访问...
[[NSBundle mainBundle] objectForInfoDictionaryKey:key_name];
例如,要获取版本号,您可以执行以下操作
NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
有一个问题是版本号现在在 info.plist 中有两个属性 - 但你明白了吗?如果您将 info.plist 视为源代码(右键单击 info.plist - 选择 Open As),那么您将看到您可以使用的所有各种键名。
Damo's solution 的 Swift 4+ 语法
Bundle.main.object(forInfoDictionaryKey: "KEY_NAME")
例子
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion")
Bundle
需要 import SystemConfiguration
那么你可以很容易地访问 info.plist :
获取故事板的名称:
NSString *storyboard = [[NSBundle mainBundle].infoDictionary objectForKey:@"UIMainStoryboardFile"];
不确定它是否会检测到它是否在 iPad 中并且应该使用已设置的 UIMainStoryboardFile~ipad
键。
NSString *path = [[NSBundle mainBundle] pathForResource: @"YOURPLISTNAME" ofType: @"plist"];
NSMutableDictionary *dictplist =[[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
您还可以在 NSBundle 上使用 infoDictionary 方法:
NSDictionary *infoPlistDict = [[NSBundle mainBundle] infoDictionary];
NSString *version = infoPlistDict[@"CFBundleVersion"];