项目有些需求可能需要获取项目的名字,这里只是简单的写下自己的想法
项目名字、版本号等属性是plist文件形式维护的,需要拿到bundle文件中管理各种属性的字典,根据相应的key去获取对应的值。
[[NSBundle mainBundle] infoDictionary];
复制代码
打印其数据:
{
BuildMachineOSBuild = 15G1217;
CFBundleDevelopmentRegion = en;
CFBundleExecutable = GetAppName;
CFBundleIdentifier = "com.cai.GetAppName";
CFBundleInfoDictionaryVersion = "6.0";
CFBundleName = GetAppName;
CFBundleNumericVersion = 16809984;
CFBundlePackageType = APPL;
CFBundleShortVersionString = "1.0";
CFBundleSupportedPlatforms = (
iPhoneSimulator
);
CFBundleVersion = 1;
DTCompiler = "com.apple.compilers.llvm.clang.1_0";
DTPlatformBuild = "";
DTPlatformName = iphonesimulator;
DTPlatformVersion = "10.2";
DTSDKBuild = 14C89;
DTSDKName = "iphonesimulator10.2";
DTXcode = 0821;
DTXcodeBuild = 8C1002;
LSRequiresIPhoneOS = 1;
MinimumOSVersion = "10.2";
UIDeviceFamily = (
1
);
UILaunchStoryboardName = LaunchScreen;
UIMainStoryboardFile = Main;
UIRequiredDeviceCapabilities = (
armv7
);
UISupportedInterfaceOrientations = (
UIInterfaceOrientationPortrait,
UIInterfaceOrientationLandscapeLeft,
UIInterfaceOrientationLandscapeRight
);
}
复制代码
//CFBundleExecutable -> 获取项目工程名
//CFBundleIdentifier -> 获取应用唯一标识
//CFBundleName -> 获取项目工程名
//CFBundleShortVersionString -> 获取应用版本号 (App Store上版本号 -> Version)
//CFBundleVersion -> 获取应用内部版本号(Build)
复制代码
#####默认
- 新建一个项目,工程名设置为: GetAppName,其他不做任何修改,输出相关key的值:
NSLog(@"--%@--%@--%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]);
复制代码
- Output:
--GetAppName--GetAppName--(null) --> 因为Display Name未设置 则不存在此key的值
复制代码
#####仅设置Display Name
//1. Display Name不为空: --> 工程 -> TARGETS -> General -> Identity -> Display Name: 简书-创作你的创作
NSLog(@"-%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]);
//输出: -简书-创作你的创作
复制代码
#####仅设置Info.plist中Bundle name的值为中文
//2. Display Name 为空: --> Info.plist文件中Bundle name的值修改app名字为中文 例如: 简书
NSDictionary *appInfo = [[NSBundle mainBundle] infoDictionary];
NSLog(@"%@", [appInfo objectForKey:(NSString *)kCFBundleNameKey]);
//输出: 简书
复制代码
#####既设置Info.plist中Bundle name的值为中文又设置Display Name
//3.Info.plist文件中Bundle name的值修改app名字为中文 例如: 简书 并且 修改设置Display Name: 简书-创作你的创作
NSLog(@"--%@--%@--%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleExecutable"], [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]);
//输出: --简书--GetAppName--简书-创作你的创作
复制代码
PS: 两者均设置的情况下,手机界面显示的应用名字和Display Name设置的名字保持一致。
建议使用仅设置Info.plist中Bundle name的值的方式设置应用名字,这样在获取应用名字的时候,防止使用CFBundleDisplayName不存在造成获取值为空。
#####如何拿到应用名字、版本号等key:
除了直接使用代码方式将其打印出来,还可以如下图:
或者