1

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.

1
  • It is similar - and trust me I had been looking for that question unsuccessfully for an hour before asking mine - but since this question has a specific example which has now been correctly resolved, I'd say it's different enough. Thank you for the link though.
    – SG1
    Nov 6, 2012 at 18:19

1 Answer 1

3

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
2
  • This works, but I haven't tested device vs simulator. Apparently the TARGET_OS_IPHONE distinguishes these, where what I want is to distinguish Mac vs iOS, regardless of device.
    – SG1
    Nov 6, 2012 at 19:34
  • I'm not sure where you picked up the idea that TARGET_OS_IPHONE evaluates differently between a device and the simulator, I've never heard that. If you want a macro to test for the simulator use TARGET_IPHONE_SIMULATOR. TARGET_OS_IPHONE evaluates true for an iOS target.
    – NJones
    Nov 6, 2012 at 20:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.