How to automatically choose between NSColor and UIColor for the correct build system? (Using #define or something else)

I am trying to create a subclass of NSObject that will have many methods that return colors, so I want to return UIColor if I create for iOS or NSColor if I create for OS X.
This is a kind of pseudo-code of expected behavior:

 #define COLOR #if TARGET_OS_IPHONE UIColor #elif TARGET_OS_MAC NSColor #endif + (COLOR *)makeMeColorful; 

Is it possible to do something like this instead of doing 2 methods for each of my object methods (one for iOS and the other for OS X)?

+8
c-preprocessor objective-c cocoa uicolor nscolor
source share
3 answers

It is absolutely doable. For example, SKColor from SpriteKit is defined as:

 #if TARGET_OS_IPHONE #define SKColor UIColor #else #define SKColor NSColor #endif 

And then used as follows:

 SKColor *color = [SKColor colorWithHue:0.5 saturation:1.0 brightness:1.0 alpha:1.0]; 

It just takes advantage of the fact that UIColor and NSColor use some of their class methods.

+13
source share

If you use Swift, try something in the lines

 #if os(macOS) typealias Color = NSColor #else typealias Color = UIColor #endif 

Works for macOS, iOS, tvOS and watchOS. Read more about Swift Preprocessor Directives .

+5
source share

You can use typedef in the preprocessor conditionally:

 #if TARGET_OS_IPHONE typedef UIColor MONPlatformColor; #elif typedef NSColor MONPlatformColor; #endif 

And your API will be declared:

 + (MONPlatformColor *)makeMeColorful; 
+2
source share

All Articles