Search code examples
objective-cmacoscategoriesosx-mountain-lionnscolor

Conditional categories in Mountain Lion


Mountain Lion introduced new APIs, some of which we had implemented as categories in our project.

For examples, we have a category NSColor+CGColorAdditions that implemented CGColor and colorWithCGColor: for NSColor. These methods have been added in Mountain Lion.

Ideally, we would like to use these categories if the client OS is older than Mountain Lion, and not use them if it's Mountain Lion. How can we do this? Or is there a better alternative?


Solution

  • NSColor *_NSColor_colorWithCGColor_(Class self, SEL cmd, CGColorRef cgColor)
    {
        // make an NSColor outta `cgColor` and return it
        return nsColor;
    }
    
    // inside some initialization code
    
    if ([[NSColor class] respondsToSelector:@selector(colorWithCGColor:)]) {
        // on ML, don't do anything
    } else {
        // older system, add your own category
        class_addMethod(objc_getMetaClass("NSColor"), @selector(colorWithCGColor:), (IMP)_NSColor_colorWithCGColor_, "@@:@");
    }