【问题标题】:iPhone: Suppress NSLog in production?iPhone:在生产中抑制 NSLog?
【发布时间】:2011-10-08 05:10:50
【问题描述】:

我的代码中有一堆 NSLog 语句。无论如何我可以抑制它们在生产中执行,但在我开发时执行?我不想将它们注释掉,他们在开发时将它们放回原处,因为这很麻烦。

【问题讨论】:

标签: iphone


【解决方案1】:

DEBUG 是一个宏,仅在您对项目进行调试/开发构建时定义(xcode 默认)。这将导致 #ifdef DEBUG#endif 行之间的任何代码在进行 release 构建时不包含在内,但它们将被编译并包含在 debug/dev/test 构建中。

例子:

#ifdef DEBUG
    NSLog(@"Hello World!");
#endif

这是我在Project-Prefix.pch 文件中使用的(用DEBUGLOG(@"abc %@", someStr); 调用):

#ifdef DEBUG
    extern void DBGQuietLog(NSString *format, ...);
    #define DEBUGLOG(fmt, ...) DBGQuietLog((@"[Line: %d] %s: " fmt), __LINE__, __FUNCTION__, ##__VA_ARGS__);
#else
    #define DEBUGLOG(fmt, ...)
#endif

#ifdef DEBUG
    void DBGQuietLog(NSString *format, ...) {
        if (format == nil) {
            printf("nil\n");
            return;
        }
        va_list argList;
        va_start(argList, format);
        NSString *s = [[NSString alloc] initWithFormat:format arguments:argList];
        printf("%s\n", [[s stringByReplacingOccurrencesOfString:@"%%" withString:@"%%%%"] UTF8String]);
        [s release];
        va_end(argList);
    }
#endif

这会打印带有行号、类名和方法名的控制台行(仅在调试时),如下所示:

[Line: 36] -[iPhoneAppDelegate application:didFinishLaunchingWithOptions:]: Hello World!

【讨论】:

  • 当我将它放入我的 prefix.pch 时,我收到多个链接器警告:duplicate symbol _DBGQuietLog.
  • @glasz 这可能意味着您已经在其他地方定义了 DBGQuietLog。在您的项目中搜索 DBGQuietLog 并查看该名称是否已被使用。要修复它,您只需将 DBGQuietLog 重命名为 DBGQuietLog1 (不要忘记更改所有使用它的 3 个位置的名称)。
  • 我确实做到了。重命名它(尽管搜索没有出现任何重复)并且链接器仍然抱怨重命名的方法已经存在 0.o
  • @glasz 我认为您不止一次包含前缀头文件。
【解决方案2】:

您可以创建一个代理并将其定义为预处理器宏:

#ifdef DEBUG
#define MyLog(str, ...) NSLog(str, ##__VA_ARGS__)
#else
#define MyLog(str, ...) 
#endif

然后你会在你的代码中使用 MyLog() 而不是 NSLog() 并且当不在调试模式下编译时,NSLog 将被替换为无操作。

【讨论】:

    【解决方案3】:

    作为 CajunLuke 答案的扩展,我只能建议您使用这个:http://kdl.nobugware.com/post/2009/03/11/better-nslog/

    【讨论】:

      【解决方案4】:

      用宏包装它们。不幸的是,Apple 还没有通过“罐装”解决方案这样做,但很多人都这样做了,而且网络上有很多例子。

      类似:

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

      (希望是正确的——从另一个屏幕手动复制)

      【讨论】:

        猜你喜欢
        • 2015-05-04
        • 1970-01-01
        • 1970-01-01
        • 2015-01-09
        • 2017-12-23
        • 1970-01-01
        • 2011-07-05
        • 1970-01-01
        • 2021-07-15
        相关资源
        最近更新 更多