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

查看:24
本文介绍了真的不应该在生产代码上使用 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 会自动去除这些调用.

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 对象交互来构建更复杂的日志记录系统.例如,您可以拥有一个写入其自己的日志文件(或数据库)的日志记录类,并包含您可以在运行时设置的优先级"参数,因此您的发布版本中不会显示调试消息,但错误消息是(如果你这样做了,你就可以创建 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 可以在您的应用程序的不同位置重复使用.例如,在我的应用程序中,我使用它来禁用许可证密钥检查,并且只允许应用程序在某个日期之前运行.这让我能够以最少的工作量分发时间有限、功能齐全的测试版副本.

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天全站免登陆