如何仅在设置标志时才将代码包含到构建中?
我在我的应用程序中添加了一些调试代码,我只想在需要时调用它们。我记得有某种 IFDEF
可用于有条件地将代码包含到源文件中。
例如,我可能有这样的内容:
IFDEF kDebugEnabled == YES {
// some debugging code here
}
然后,如果 kDebugEnabled 为 YES,那么这段代码只会编译成二进制文件。
我怎样才能做这样的事情?
请注意:我不想使用项目编译器标志设置。我只想定义一个布尔值(或者也可以达到目的的东西),它是 true 或 false,然后轻松地在我的 App Delegate 中设置它。我发现很难导航到项目编译器设置、搜索标志然后设置它。我知道有一个可能有用的调试标志。
I have added some debugging code to my app which I want to call only when needed. I remember there is some kind of IFDEF
that can be used to conditionally include code into a source file.
For example I might have something like this:
IFDEF kDebugEnabled == YES {
// some debugging code here
}
And then this piece of code is only compiled into the binary if that kDebugEnabled is YES.
How can I do something like this?
Please note: I don't want to use the project compiler flag settings. I just want to define a BOOL (or something that serves the purpose just as well) which is true or false and then just easily set it in my App Delegate for example. I find it hard to navigate to the project compiler settings, searching for a flag and then setting it. I know there is a Debug flag which might be of use.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找的是:
您可以以编程方式定义
__YOURSYMBOL__
,如下所示:__YOURSYMBOL__
可以是任何对您有意义的字符串,以记住为什么要包含/排除该代码片段。DEBUG 常量是一个特殊的预处理器常量,编译器在构建代码进行调试时专门为您定义,因此您可以简单地使用它:
请考虑到这是 C 预处理器,而不是 C ,也不是您正在使用的 Objective-C,因此像
kDebugEnabled == YES
(其中 kDebugEnabled 是 Objective-C 变量)这样的测试根本不可能。您可以为常量定义整数值,如下所示:然后对其进行测试:
What you are looking for is:
You can programmatically define
__YOURSYMBOL__
like this:__YOURSYMBOL__
can be any string that makes sense to you to remember why you are including/excluding that code snippet.The
DEBUG
constant is a special preprocessor constant that the compiler defines specifically for you when the code is built for debugging, so you can simply use it:Take into account that this is the C-preprocessor, not C, nor Objective-C that you are using, so a test like
kDebugEnabled == YES
(where kDebugEnabled is an Objective-C variable) is simply not possible. You can define integer values for your constants, like this:and then test for it:
据我所知,如果不使用编译器标志,类中就不能包含未编译到最终产品中的代码。然而,使用 DEBUG 标志比您想象的要容易得多。如果您使用的是 Xcode 4,它是默认设置的。
默认情况下,Xcode 有两种配置:
Debug
和Release
。当您使用调试构建配置时,除其他外,它会设置 DEBUG 编译器标志,然后您可以使用该标志来有条件地编译代码。根本不需要搞乱编译设置。As far as I know, you can't have code in your classes that is not compiled into the final product without using compiler flags. However, using the DEBUG flag is a lot easier than you think. If you are using Xcode 4, it's set up for you by default.
Xcode has, by default, two configurations,
Debug
andRelease
. When you use the debug build configuration, among other things, it sets the DEBUG compiler flag, which you can then use to conditionally compile code. No need to mess with compilation settings at all.