How to know what Mac OS the app is running on?

后端 未结 7 2002
遥遥无期
遥遥无期 2020-12-31 18:30

I\'ve seen in some projects something like:

#if .....
    code...
#endif

but i can\'t find it now...
Let\'s say, for example, if the ap

7条回答
  •  梦毁少年i
    2020-12-31 18:49

    You're probably asking the wrong question. Except in very rare cases, you should not care what system version the user is running. Instead, you should be checking if the specific thing you're interested in is available.

    For instance, if Apple introduces a MagicHologram class in Mac OS X 10.9 that you want to use, you don't check if the user is running Mac OS X 10.9. Instead, you check if the MagicHologram class is available. If it is, you can use it. If not, it's not available. It doesn't even matter why. Maybe they're running 10.8. But maybe it's five years later, and Apple's decided to drop the MagicHologram class entirely.

    (Also, keep in mind that you'd need to weak link to HologramKit, the library that provides the MagicHologram class.)

    Likewise, if they introduce a new method to NSString, instead of checking the OS version you'd check if NSString knows about the new method.

    That said, NSApplication.h includes an external constant called NSAppKitVersionNumber. You can compare this to constants like NSAppKitVersionNumber10_7 which (it should be noted) are numbers like 1138, not 10.7. There's only a few places this is appropriate, mostly where classes were private and undocumented but got major changes before being documented and becoming a part of the public parts of the SDK. Also, it might be helpful if you want to avoid a specific bug that's been fixed since.

    To recap:

    1. Detect individual classes and methods, which should cover 99.44% of your cases.
    2. Use NSAppKitVersionNumber and NSAppKitVersionNumber10_7 to cover those cases where class or method detection would lie to you.
    3. Those first two points cover all normal cases. You should go no further. But if you must have behaviour based on humane version, look at abarnert's answer below. It's the sanest way to get them.
    4. Don't use operatingSystemVersionString, which is specifically listed as not safe for parsing.

    References/more information:

    • SDK Compatibility Guide "Read this document if you want your application to target a specific version or multiple versions of iOS or Mac OS X."
      • Using SDK-Based Development Describes how to use weakly linked classes, methods, and functions to support running on multiple versions of an operating system.

提交回复
热议问题