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 t开发者_开发知识库he 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.
精彩评论