Objective-C:从'Distribution'/ production builds中删除NSLog调用?

时间:2012-08-26 23:38:20

标签: objective-c ios ios5

更新

有关这方面的更多信息:

Is it true that one should not use NSLog() on production code?

~~~~~~~~~~~~~~~~~~~~~~~~

场合

我有一些非常好的NSLog调用,我用它来调试应用程序中更复杂的部分。但是,我刚刚了解到这些会影响运行时性能!

目标

我想在任何我没有执行Product>的运行期间删除我的NSLog调用。在Xcode中运行(也就是命令-R) - 特别是在App Store上部署此东西的情况下,以及当我从Xcode断开连接时运行应用程序时(即只是在街上行走时点击图标)。 / p>

建议的解决方案?

假设我已经创建了VIEW_DEBUG的预处理器宏,那么下面的实现是否会有效地从上面描述的情况中删除NSLog调用?

    <bunch of code>

#ifdef VIEW_DEBUG
    NSLog(@"really complex logs entries");
#endif

    <even more code>

这对我来说是“难以测试”的,所以我认为我会吸引更多有经验的人。 :)

Xcode设置(供参考)

xcode settings

2 个答案:

答案 0 :(得分:12)

一个常见的解决方案是将以下代码放在您的前缀文件中(或者您可以根据需要创建专用类和#include):

#ifdef DEBUG    
#define DebugLog(...) NSLog(__VA_ARGS__)
#else
#define DebugLog(...) while(0)
#endif

Xcode在执行调试构建时已经为您定义了DEBUG(如屏幕截图所示)。 VA_ARGS 是一种创建C99中引入的variadic macros的方法。 do/while确保DebugLog 即使它没有做任何事情也具有相同的净语法效果 - 不要担心无意义的循环,优化器会为你删除它。

然后,您可以使用DebugLog,就像使用NSLog一样。这将完全符合您对VIEW_DEBUG提出的建议,但无需将#ifdef条件复制并粘贴一千次。

答案 1 :(得分:3)

我总是在代码中使用DLog,效果很好。

// DLog is almost a drop-in replacement for NSLog
// DLog();
// DLog(@"here");
// DLog(@"value: %d", x);
// Unfortunately this doesn't work DLog(aStringVariable); you have to do this instead DLog(@"%@", aStringVariable);
#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#   define DLog(...)
#endif

// ALog always displays output regardless of the DEBUG setting
#define ALog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);

更多信息:The Evolution of a Replacement for NSLog

相关问题