【问题标题】:Switch on/off NSLog with a boolean just like CCLog in cocos2d使用布尔值打开/关闭 NSLog,就像 cocos2d 中的 CCLog
【发布时间】:2014-05-29 02:54:10
【问题描述】:

我有一个 IS_TESTING 布尔标志,指示当前构建是否正在测试

如果 IS_TESTING 为 NO,我想隐藏 NSLog。它还应该支持单个字符串参数。

这是来自 cocos2d 的 CCLog:

#define __CCLOGWITHFUNCTION(s, ...) \
NSLog(@"%s : %@",__FUNCTION__,[NSString stringWithFormat:(s), ##__VA_ARGS__])

#define __CCLOG(s, ...) \
NSLog(@"%@",[NSString stringWithFormat:(s), ##__VA_ARGS__])


#if !defined(COCOS2D_DEBUG) || COCOS2D_DEBUG == 0
#define CCLOG(...) do {} while (0)
#define CCLOGWARN(...) do {} while (0)
#define CCLOGINFO(...) do {} while (0)

#elif COCOS2D_DEBUG == 1
#define CCLOG(...) __CCLOG(__VA_ARGS__)
#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#define CCLOGINFO(...) do {} while (0)

#elif COCOS2D_DEBUG > 1
#define CCLOG(...) __CCLOG(__VA_ARGS__)
#define CCLOGWARN(...) __CCLOGWITHFUNCTION(__VA_ARGS__)
#define CCLOGINFO(...) __CCLOG(__VA_ARGS__)
#endif // COCOS2D_DEBUG

这是我写的:

#define __CCLOG(s, ...) \
NSLog(@"%@",[NSString stringWithFormat:(s), ##__VA_ARGS__])


#if IS_TESTING == 0
#define CCLOG(...) do {} while (0)

#elif IS_TESTING == 1
#define CCLOG(...) __CCLOG(__VA_ARGS__)

#endif

使用:

CCLOG(@"single string parameter");
CCLOG(@"string format %@", @"parameter");

它运行没有崩溃,但没有打印出来。

编辑:

#define IS_TESTING YES

我试过了 #if IS_TESTING == YES/NO,但还是和 0/1 一样,没有打印出来

【问题讨论】:

  • 你应该将 bool 定义为 int
  • FWIW,Xcode 有一个定义的“DEBUG”,定义为 1,然后自动更改为定义为 0 用于发布版本。

标签: ios objective-c cocoa-touch cocos2d-iphone uikit


【解决方案1】:

您的代码运行良好。但是IS_TESTING 必须在您开始__CCLOG 定义之前定义

所以,在 .pch 文件中,我写道:

#define IS_TESTING 1

#define __CCLOG(s, ...) \
NSLog(@"%@",[NSString stringWithFormat:(s), ##__VA_ARGS__])

#if IS_TESTING == 0
#define CCLOG(...) do {} while (0)
#elif IS_TESTING == 1
#define CCLOG(...) __CCLOG(__VA_ARGS__)
#endif

后来:

CCLOG(@"%@", @"YES");

由于我已将IS_TESTING 定义为 1,因此我们记录。如果我将其更改为 0,我们不会。


作为奖励,我将向您展示我的工作。这要简单得多。这里是:

#define MyLog if(0); else NSLog

这使得MyLog 等同于NSLog。要关闭日志记录,请将 0 更改为 1

【讨论】:

  • NSLog 不支持单字符串参数。所以你必须做 NSLog(@"%@", @"a string")
  • 是否可以将 IS_TESTING 定义为 YES 而不是 1?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2012-09-29
  • 2018-08-28
  • 2011-09-15
  • 1970-01-01
  • 2020-06-09
  • 2016-05-06
相关资源
最近更新 更多