从Info.plist中读取版本

Joh*_*ith 87 iphone xcode cocoa-touch objective-c info.plist

我想从Info.plist中读取捆绑版本信息到我的代码中,最好是作为字符串.我怎样才能做到这一点?

gca*_*amp 199

您可以将Info.plist作为字典阅读

[[NSBundle mainBundle] infoDictionary]
Run Code Online (Sandbox Code Playgroud)

而且您可以通过CFBundleVersion这种方式轻松获得密钥版本.

最后,你可以获得版本

NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
NSString* version = [infoDict objectForKey:@"CFBundleVersion"];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,在Xcode4中,如果查看目标的摘要面板,您将看到版本和构建字段.`CFBundleVersion`已被重新用作Build,Version是`CFBundleShortVersionString`. (20认同)
  • 对于版本号,这没关系,但对于其他键,您可能希望使用`objectForInfoDictionaryKey:`,因为它返回本地化值(如果可用):`[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"]` (16认同)
  • 这将获取版本和内部版本号,并将它们一起格式化:`NSString*version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];``NSString*build = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] ;``self.versionLabel.text = [NSString stringWithFormat:@"%@.%@",version,build];` (5认同)

aya*_*aya 10

对于Swift用户:

if let version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") {
    print("version is : \(version)")
}
Run Code Online (Sandbox Code Playgroud)

对于Swift3用户:

if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") {
    print("version is : \(version)")
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ler 5

我知道自寻求和回答以来已经过去了一段时间。

从iOS8开始,接受的答案可能无效。

这是现在的新方法:

NSString *version = (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey);
Run Code Online (Sandbox Code Playgroud)

  • 您是否有链接为何如此? (6认同)