首页 > 解决方案 > NSBundle mainBundle 返回 nil

问题描述

我正在尝试根据我们 iOS 应用程序的 Xcode 中的构建配置更改服务器设置。我以本指南为基础。我在 Info.plist 中设置了配置属性,但是当我尝试在代码中获取它时它又回来了nil

info.plist 条目

在寻找解决方案和测试时,我发现我正在nil从与mainBundle. 到目前为止,这是我在测试中声明的内容。我错过了什么/做错了什么?

NSBundle *bundle = [NSBundle mainBundle];
NSString *configuration = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Configuration"];
NSString *bundleName = [[NSBundle mainBundle] bundleIdentifier];
NSString *otherName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleNameKey];

我正在使用 Xcode 9.3。

标签: iosobjective-cxcodensbundle

解决方案


在某些情况下,例如当您的代码直接从 Interface Builder 中执行时,mainBundle不会返回对象。因此,根据您的上下文,您可能想要使用它bundleForClass:。指定驻留在所需捆绑包中的类。

NSBundle *bundle = [NSBundle bundleForClass:[YourClass class]];

推荐阅读