Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
700 views
in Technique[技术] by (71.8m points)

xcode - Which conditional compile to use to switch between Mac and iPhone specific code?

I am working on a project that includes a Mac application and an iPad application that share code. How can I use conditional compile switches to exclude Mac-specific code from the iPhone project and vice-versa? I've noticed that TARGET_OS_IPHONE and TARGET_OS_MAC are both 1, and so they are both always true. Is there another switch I can use that will only return true when compiling for a specific target?

For the most part, I've gotten the files to cooperate by moving #include <UIKit/UIKit.h> and #include <Cocoa/Cocoa.h> into the precompile headers for the two projects. I'm sharing models and some utility code that fetches data from RSS feeds and Evernote.

In particular, the [NSData dataWithContentsOfURL:options:error:] function takes a different constant for the options parameter iOS 3.2 and earlier and Mac OS 10.5 and earlier than it does for iOS 4 and Mac OS 10.6. The conditional I'm using is:

#if (TARGET_OS_IPHONE && (__IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_3_2)) || (TARGET_OS_MAC && (MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5))

This seems to work, but I want to make sure this is bulletproof. My understanding is that if the Mac version is set to 10.6, but the iOS version is set to 3.2, it will still use the new constants even if it's compiling for iOS 3.2, which seems incorrect.

Thanks in advance for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You've made a mistake in your observations. :)

TARGET_OS_MAC will be 1 when building a Mac or iPhone application. You're right, it's quite useless for this sort of thing.

However, TARGET_OS_IPHONE is 0 when building a Mac application. I use TARGET_OS_IPHONE in my headers all the time for this purpose.

Like this:

#if TARGET_OS_IPHONE
// iOS code
#else
// OSX code
#endif

Here's a great chart on this: http://sealiesoftware.com/blog/archive/2010/8/16/TargetConditionalsh.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...