Creating an iOS/OS X cross-platform class

后端 未结 3 464
生来不讨喜
生来不讨喜 2020-12-14 19:53

I read a lot of questions about creating a cross-platform library for these 2 systems. Every answer points to static library as the solution.

I don\'t want to end up

相关标签:
3条回答
  • 2020-12-14 20:32

    the two defines you talk about are set to 1 or 0 depending on what you compile for! (at compilation time)

    so you are on the right track here I guess

    e.g.

    #if TARGET_OS_IPHONE
    #import <CoreText/CoreText.h>
    #elif TARGET_OS_MAC
    #import <ApplicationServices/ApplicationServices.h>
    #endif
    
    0 讨论(0)
  • 2020-12-14 20:46

    When it comes to UIColor/NSColor, I handle it like this:

    #if TARGET_OS_IPHONE
    #define ImageClassName UIImage
    #else
    #define ImageClassName NSImage
    #endif
    

    Then, in header files, and if you're just passing instances around, you can just use e.g. ImageClassName *.

    Repeat the #if block in your code when you need to use the UIColor/NSColor APIs.

    0 讨论(0)
  • 2020-12-14 20:52

    The problems you're seeing arise from the fact that TARGET_OS_IPHONE is defined as a variant of TARGET_OS_MAC. (In other words, TARGET_OS_IPHONE is a more-specific case of TARGET_OS_MAC. Or TARGET_OS_MAC is to a rectangle as TARGET_OS_IPHONE is to a square).

    So the following code errors out when compiling for iOS because iOS would match both of those conditions, but NSColor is not defined for iOS.

    #if TARGET_OS_MAC
    -(void)createColor:(NSColor*)color;    
    
    #elif TARGET_OS_IPHONE
    -(void)createColor:(UIColor*)color;
    
    #endif
    

    The following code works properly for both because for iOS, it matches the first case, and for Mac OS X, it doesn't match the first but does match the second.

    #if TARGET_OS_IPHONE
    -(void)createColor:(UIColor*)color;
    
    #elif TARGET_OS_MAC
    -(void)createColor:(NSColor*)color;
    
    #endif
    
    0 讨论(0)
提交回复
热议问题