iosxcodecocoa

Use pragma ifdef to conditionally compile the same protocol header for both mac and ios?


Possible Duplicate:
Which conditional compile to use to switch between Mac and iPhone specific code?

I've defined a protocol which should work just fine on both Mac and iOS. However, one of the methods of the protocol would better return a specific class of object (rather than just 'id'), but the class is not a foundation class and thus varies on the two platforms (for example, UIButton and NSButton).

How can I use a pragma mark like #ifdef TARGET_OS_IPHONE to include the same protocol header in two libraries, one built for iOS and one for Mac?

Here is my actual protocol and my (broken) attempt at conditional compilation

#import <Foundation/Foundation.h>

@protocol SharedAppDelegate <NSObject>

#ifdef TARGET_OS_IPHONE
@protocol UIApplicationDelegate;
+ (NSObject<UIApplicationDelegate> *)sharedAppDelegate;
#else
@protocol NSApplicationDelegate;
+ (NSObject<NSApplicationDelegate> *)sharedAppDelegate;
#endif

@end

One thing I know off the bat is that the target does not include the simulator, but I cannot find a solid example of one target which covers Mac and another all iOS incarnations.


Solution

  • You're gonna kick yourself. It's #if not #ifdef. TARGET_OS_IPHONE is a #define that is set to 1 for iOS and 0 for mac. You want to use the simple #if.

    #if TARGET_OS_IPHONE
        NSLog(@"is iPhone or simulator");
    #else
        NSLog(@"is mac... probably");
    #endif
    

    Also, you can't have a forward declaration of a protocol inside a protocol definition. You'll have to do something like:

    #if TARGET_OS_IPHONE
    @protocol UIApplicationDelegate;
    #else
    @protocol NSApplicationDelegate;
    #endif
    
    
    @protocol SharedAppDelegate <NSObject>
    #if TARGET_OS_IPHONE
    + (NSObject<UIApplicationDelegate> *)sharedAppDelegate;
    #else
    + (NSObject<NSApplicationDelegate> *)sharedAppDelegate;
    #endif