在Objective-C中查找Mac OS X版本号

12

我的Cocoa Objective-C应用程序如何查找Mac OS X版本号(例如“ 10.6.7”)?


参见:https://dev59.com/bXVC5IYBdhLWcg3w4VRz - Adam Rosenfield
3个回答

25
#import <CoreServices/CoreServices.h>

SInt32 major, minor, bugfix;
Gestalt(gestaltSystemVersionMajor, &major);
Gestalt(gestaltSystemVersionMinor, &minor);
Gestalt(gestaltSystemVersionBugFix, &bugfix);

NSString *systemVersion = [NSString stringWithFormat:@"%d.%d.%d",
    major, minor, bugfix];

6
请注意,此代码已被弃用。建议查看链接文章。 - Brett
1
根据苹果工程师David Smith(化名Catfish_Man)的说法,使用Gestalt来表示版本号是可以的。请参见他的推文 - user557219
1
Bavarious 这很有趣,但这只表明苹果公司的左右手并不总是知道彼此在做什么。除非代码确实过时了,否则不应将其标记为已弃用。 - Brett
@Bavarious 如果我们想要OSX的实际名称,例如LION等,该怎么办?谢谢。 - Vikas Bansal

19

你可以使用和苹果代码相同的技术...

NSDictionary *systemVersionDictionary =
    [NSDictionary dictionaryWithContentsOfFile:
        @"/System/Library/CoreServices/SystemVersion.plist"];

NSString *systemVersion =
    [systemVersionDictionary objectForKey:@"ProductVersion"];

苹果正是通过函数_CFCopySystemVersionDictionary在这里填写各种系统实用程序的版本号:

http://opensource.apple.com/source/CF/CF-744/CFUtilities.c


这会在沙盒应用上运行吗?在我看来,最好始终使用系统API。 - Jay

12

对于 OS X 10.10+,我认为使用 NSProcessInfo 是更简单和更安全的方法:

NSOperatingSystemVersion version = [[NSProcessInfo processInfo] operatingSystemVersion];
NSLog([NSString stringWithFormat:@"%ld.%ld.%ld", version.majorVersion, version.minorVersion, version.patchVersion]);

1
operatingSystemVersion 方法是在 OS X 10.10 中新增的,因此在早期的答案编写时它并不存在。 - JWWalker

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接