How can I determine the running Mac OS X version programmatically?

余生颓废 提交于 2019-11-27 21:25:12
Nik Reiman

See this article here

But in short, if you're using carbon, use the Gestalt() call, and if you're using cocoa, there is a constant called NSAppKitVersionNumber which you can simply check against.

Edit: For Mac OSX 10.8 and above, don't use Gestalt() anymore. See this answer for more details: How do I determine the OS version at runtime in OS X or iOS (without using Gestalt)?

Could you just check for the presence of a capability? For instance:

if (NSClassFromString(@"NSKeyedArchiver") != Nil)

or

if ([arrayController respondsToSelector: @selector(selectedIndexes)])

then you know that the operating system does what you need it to do, not that Apple's product marketing group gave it a particular number ;-)

The API is through the Gestalt Manager.

See "Determining OS Version" in the CocoaDev site.

In terminal:

system_profiler SPSoftwareDataType

Gives:

Software:

    System Software Overview:

      System Version: Mac OS X 10.5.5 (9F33)
      Kernel Version: Darwin 9.5.0
      Boot Volume: Main
      Boot Mode: Normal
      Computer Name: phoenix
      User Name: Douglas F Shearer (dougal)
      Time since boot: 2 days 16:55

Or:

sw_vers

Gives:

ProductName:    Mac OS X
ProductVersion: 10.5.5
BuildVersion:   9F33

Is the OS version really what you want? There may be a more appropriate thing to test for, such as the presence of, or version number of, a particular framework.

within your program you can use Gestalt. Here is the code I am using for my program to obtain the OS version.

long version = 0;
OSStatus rc0 = Gestalt(gestaltSystemVersion, &version);
if((rc0 == 0) && (version >= 0x1039)) {      
    // will work with version 10.3.9
    // works best with version 10.4.9
    return; // version is good
}
if(rc0) {
    printf("gestalt rc=%i\n", (int)rc0);
} else {
    printf("gestalt version=%08x\n", version);
}

respondsToSelector: almost certainly is better than you maintaining a table of what given releases do and do not implement.

Be lazy. Let the runtime tell you whether it can do something or not, and fall back to older methods when you need to. Your code will be far less fragile because you don't have to maintain your own global data that the rest of your code has to keep checking with.

Run this in the command line:

system_profiler SPSoftwareDataType | grep Mac
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!