简体   繁体   中英

Conditional Methods based on Operating System Version

I am sure this is really simple, but I'm not sure even how to search for it, as I have seen example of what I think are called compiler flags?, but in general whats the best method in cocoa of condtionally running a specific method on Operating System Versions that support it. as an example the NSDateFormatter Class has the setDoesRelativeDateFormatting method which only works on 10.6 (on the Mac) and higher.

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];        
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

    [dateFormatter setLocale:enLocale];
    [dateFormatter setDoesRelativeDateFormatting:YES];

Here's how Adium detected that it was running on Snow Leopard or better to do stuff like this (this was in a category on NSApplication):

//Make sure the version number defines exist; when compiling in 10.5, NSAppKitVersionNumber10_5 isn't defined 
#ifndef NSAppKitVersionNumber10_5
#define NSAppKitVersionNumber10_5 949
#endif 

- (BOOL)isOnSnowLeopardOrBetter
{
    return (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_5);
}

Then all you have to do is

if ([NSApp isOnSnowLeopardOrBetter]) { ... }

You can find the version numbers for AppKit by command-clicking on NSAppKitVersionNumber to jump to its definition.

For this particular case, it should be easy enough to do the following:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];        
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

[dateFormatter setLocale:enLocale];

if ([dateFormatter respondsToSelector:@selector(setDoesRelativeDateFormatting:)]) {
    [dateFormatter setDoesRelativeDateFormatting:YES];
}

See NSObject protocol's -respondsToSelector: for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM