是不是应该在生产代码上使用NSLog()? [英] Is it true that one should not use NSLog() on production code?

查看:92
本文介绍了是不是应该在生产代码上使用NSLog()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这个网站上被告知了几次,但我想确保情况确实如此。

I was told this a few times in this very site, but I wanted to make sure this is really the case.

我原本希望能够撒上NSLog函数调用我的代码,并且Xcode / gcc会在构建我的Release / Distribution版本时自动删除这些调用。

I was expecting to be able to sprinkle NSLog function calls throughout my code, and that Xcode/gcc would automatically strip those calls out when building my Release/Distribution builds.

我应该避免使用它吗?如果是这样,有经验的Objective-C程序员之间最常见的选择是什么?

Should I avoid using this? If so, what alternatives are most common between experienced Objective-C programmers?

推荐答案

预处理器宏确实非常适合调试。 NSLog()没有任何问题,但是使用更好的功能定义自己的日志记录功能很简单。这是我使用的,它包括文件名和行号,以便更容易追踪日志语句。

Preprocessor macros are indeed great for debugging. There's nothing wrong with NSLog(), but it's simple to define your own logging function with better functionality. Here's the one I use, it includes the file name and line number to make it easier to track down log statements.

#define DEBUG_MODE

#ifdef DEBUG_MODE
    #define DebugLog( s, ... ) NSLog( @"<%p %@:(%d)> %@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
    #define DebugLog( s, ... ) 
#endif

我发现将整个语句放在前缀头而不是自己的文件中更容易。如果需要,可以通过让DebugLog与普通的Objective-C对象进行交互来构建更复杂的日志系统。例如,您可以拥有一个写入其自己的日志文件(或数据库)的日志记录类,并包含您可以在运行时设置的'priority'参数,因此调试消息不会显示在您的发行版本中,但错误消息是(如果你这样做,你可以创建DebugLog(),WarningLog(),等等。)

I found it easier to put this entire statement in the prefix header rather than its own file. You could, if you wanted, build a more complicated logging system by having DebugLog interact with normal Objective-C objects. For instance, you could have a logging class that writes to its own log file (or database), and includes a 'priority' argument you could set at runtime, so debug messages are not shown in your release version, but error messages are (if you did this you could make DebugLog(), WarningLog(), and so on).

哦,请记住 #define DEBUG_MODE 可以在应用程序的不同位置重复使用。例如,在我的应用程序中,我使用它来禁用许可证密钥检查,并且只允许应用程序在特定日期之前运行。这让我可以轻松地分发一个限时的,功能齐全的beta版本。

Oh, and keep in mind #define DEBUG_MODE can be re-used in different places in your application. For example, in my application I use it to disable license key checks and only allow the application to run if it's before a certain date. This lets me distribute a time limited, fully functional beta copy with minimal effort on my part.

这篇关于是不是应该在生产代码上使用NSLog()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆