【发布时间】:2017-01-06 10:49:09
【问题描述】:
我以前使用预处理器宏来定义常量,然后发现它们不是一个好主意。它们位于名为Global.h 的头文件中。所以我创建了一个Global.m 文件并从 git 中忽略了它的内容:
#if DEBUG
BOOL const GodMode = YES;
BOOL const TutorialDisabled = YES;
#elif STAGING
BOOL const GodMode = YES;
BOOL const TutorialDisabled = NO;
#else
BOOL const GodMode = NO;
BOOL const TutorialDisabled = NO;
#endif
以及具有此内容的Global.h:
extern BOOL const GodMode;
extern BOOL const TutorialDisabled;
STAGING 宏在项目设置的Preprocessor Macros 中定义,我的自定义Configuration 命名为Staging 为STAGING=1。
DEBUG 宏是 Xcode 生成的默认宏,类似于 staging:DEBUG=1。
有时,我想编写只为 Debug 配置执行的代码,而不需要添加新常量。
于是我开始使用:
#if DEBUG
// do something
#endif
具有这些优点/缺点:
-
优点:
-
// do something甚至不存在于其他配置中,因此应用程序大小不会增加,并且不会出现拼写错误或其他东西(例如添加!)的风险,这将导致它在以下情况下运行不需要
-
-
缺点:
- “不必要的编译文件”问题又回来了;每次更改运行配置时,需要重新编译使用此配置的文件,这增加了构建时间
- 奇怪的语法风格;我不知道我是否应该增加
// do something的缩进以匹配#if或其周围的代码,或者我是否应该像上面那样添加空行,或者它们是否应该在开头与代码在同一缩进级别的行;有类似的东西:
if (Debug) {
// do something
}
听起来是个更好的主意,所以我将Global.h 更改为:
extern BOOL const Debug;
extern BOOL const Staging;
extern BOOL const Release;
extern BOOL const GodMode;
extern BOOL const TutorialDisabled;
和Global.m:
#if DEBUG
BOOL const Debug = YES;
BOOL const Staging = NO;
BOOL const Release = NO;
BOOL const GodMode = YES;
BOOL const TutorialDisabled = YES;
#elif STAGING
BOOL const Debug = NO;
BOOL const Staging = YES;
BOOL const Release = NO;
BOOL const GodMode = YES;
BOOL const TutorialDisabled = NO;
#else
BOOL const Debug = NO;
BOOL const Staging = NO;
BOOL const Release = YES;
BOOL const GodMode = NO;
BOOL const TutorialDisabled = NO;
#endif
它成功了。
由于某种原因,
static BOOL const Debug = DEBUG;
static BOOL const Staging = STAGING;
static BOOL const Release = (!DEBUG && !STAGING);
抛出错误Use of undeclared identifier 'STAGING',即使它的定义与DEBUG 完全相同:这意味着其他配置没有DEBUG=0:
//:configuration = Debug
GCC_PREPROCESSOR_DEFINITIONS = DEBUG=1
//:configuration = Staging
GCC_PREPROCESSOR_DEFINITIONS = STAGING=1
//:configuration = Release
但是,查看 Preprocess 助理编辑器视图,if (Debug) { 出现了。
我的问题是,if 检查实际上是否会保留在例如发布配置的代码中?如果是,有没有更好的方法来实现我之前描述的?
【问题讨论】:
标签: objective-c constants