您的位置:首页 > 移动开发 > IOS开发

iOS开发:Debug与Release版本NSLog屏蔽方法

2012-11-27 18:21 531 查看
在开发过程中一般会用到NSLog(<#NSString *format, ...#>)来获得具体的信息。

但当我们发布app时,一步一步的去找NSLog(<#NSString *format, ...#>),并屏蔽掉,这样比较浪费时间还很累。我们可以采用预编译的方式来简化这个问题。
 
1.在***-Prefix.pch里面添加
#ifdef DEBUG
#    define DLog(...) NSLog(__VA_ARGS__)
#else
#    define DLog(...) /* */
#endif
#define ALog(...) NSLog(__VA_ARGS__)


2.进入Xcode 4,选择菜单“Product”->“Manage Schemes”,选择一个项目,点击“Edit”,Bulid Configuration

 

附: 检查DEBUG标志是否正确定义,xcode一般会在debug运行配置项里面已经定义号了DEBUG标志,如果没定义我们就自己写上,以我的xcode 4 为例,如下图:

 


  找到PreProcessor Macros 这个属性,对于Debug配置我们给他写上DEBUG,而在Release配置中把它留空。 这样我们刚才那段预处理命令就可以根据这个标志来判断我们编译的时调试版本还是发布版本,从而控制NSLog的输出。 (因为xcode 4 会把debug/release 两个配置项同时对比展现出来,而3.x版本的只能分别设置, 如果你用的时xcode 3.x 开发工具, 那么就分别对Debug/Release 都检查一下)。

Dropping NSLog in release builds

NSLog() is a great tool that helps debugging efforts. Unfortunately it is expensive, especially on the iPhone, and depending on how it’s used or what you’re logging, it could leak sensitive or proprietary information. If you look around the web, you’ll find
a few different ways to drop NSLog in your release builds. Here is what I’ve put together based on those.

First add the following to the <AppName>_Prefix.pch file in your Xcode project:

1
2
3
4
5
6

#ifdef DEBUG
#    define DLog(...) NSLog(__VA_ARGS__)
#else
#    define DLog(...) /* */
#endif
#define ALog(...) NSLog(__VA_ARGS__)

Right-click on your target and click Get Info. Select the
Build
tab. Make sure Configuration is set to Debug. Add
-DDEBUG to the Other C Flags of your target.

And that’s about it. When you want to log only in debug builds use DLog(). In release builds DLog() will be compiled as an empty comment. Otherwise use ALog() for logging in both debug and release builds. (A as in always.)

I like this approach for a few reasons:

Some approaches comment out all NSLog() statements when compiled. This approach lets me keep some logging if I want.
Using ALog() and DLog(), I make a conscious choice about which builds I’m going to log in.
There is very little setup.
There is no overhead. Because DLog() is defined as NSLog(), executing DLog() is no different than executing NSLog()
If you’d like to replace NSLog with DLog in your source files, here’s a quick sed command that you can run in Terminal:
$ sed -i ".bak" 's/NSLog/DLog/' *.m
FYI, this will make a backup of each of the .m files whether it changed them or not.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: