TARGET_OS_IPHONE and ApplicationTests

时间秒杀一切 提交于 2019-11-29 16:26:01

问题


Why doesn't this code work when compiling an ApplicationTests unit test bundle?

#if TARGET_OS_IPHONE
   #import <Foundation/Foundation.h>
   #import <UIKit/UIKit.h>
#else
   #import <Cocoa/Cocoa.h>
#endif

One of my dependencies has this check and compiles just fine in my main application bundles, but it tries to load <Cocoa/Cocoa.h> when compiling my ApplicationTests bundle. It's probably just my lack of understanding of Xcode, but I get nervous when my test bundles don't build. Any suggestions?


回答1:


I had a similar problem: TARGET_OS_IPHONE isn't defined when building a static library. My solution was to add "-DTARGET_OS_IPHONE" to the "Other C Flags" section of the target build options.




回答2:


You need to add

#import "TargetConditionals.h" 

source: https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-8A428/TargetConditionals.h.auto.html




回答3:


The simplest solution is to move the #import <Foundation/Foundation.h> statement out if the #if condition and replace Cocoa with AppKit like this:

#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
   #import <UIKit/UIKit.h>
#else
   #import <AppKit/AppKit.h>
#endif

The Foundation umbrella header imports the NSObjCRuntime header which in turn imports the TargetConditionals header.




回答4:


It imposes no performance penalty, although it can hurt compile times. That said, it isn't really an issue for Objective C. However, it can really hurt when dealing with C++ classes.



来源:https://stackoverflow.com/questions/3742525/target-os-iphone-and-applicationtests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!