Search code examples
iosobjective-cmacosobjective-c-category

Can I use one class category extension .h and .m file for iOS and OSX?


Is there a way to have one header and implementation file for both OSX categories and iOS categories? I don't want to make the methods the exact same and add another two files.

I've tried this, which doesn't work:

#if TARGET_OS_IPHONE
#define kClass [UIColor class]
#import <UIKit/UIKit.h>
#elif TARGET_OS_MAC
#define kClass [NSColor class]
#import <AppKit/AppKit.h>
#endif

@interface kClass (MyCategory)

Is there a way to do this?


Solution

  • Absolutely! Just remember that #define is a simple text replacement before compilation: you want kClass to be UIColor, not [UIColor class], just as you would never write @interface [UIColor class] (MyCategory).

    In conclusion:

    #if TARGET_OS_IPHONE
    #define kClass UIColor
    #import <UIKit/UIKit.h>
    #elif TARGET_OS_MAC
    #define kClass NSColor
    #import <AppKit/AppKit.h>
    #endif
    
    @interface kClass (MyCategory)