清理NSLog – 没有时间戳和程序名称
我几乎用这个代码完成一个干净的NSLog:
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, __VA_ARGS__] UTF8String]);
这工作很好,如果我这样做:
NSLog(@"Show %@ message", @"this");
但是,如果我用它,将会失败
NSLog(@"One argument");
因为__VA_ARGS__
什么__VA_ARGS__
是,所以它产生
printf("%s\n", [[NSString stringWithFormat:@"One argument",] UTF8String]);
所以,问题是逗号。 因为这是macros, __VA_ARGS__
是什么都没有。 所以我不能做像__VA_ARGS__==nil
这样的事情,因为会产生==nil
并会失败。
问题很简单:当__VA_ARGS__
是什么时, __VA_ARGS__
怎么办? 或者只有在有更多参数时才使用逗号。
– 编辑 –
许哲解决问题! 要成为最好的代码,可以这样使用它:
#ifdef DEBUG #define NSLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]); #else #define NSLog(...) #endif
现在,不再有凌乱的日志!
使用这个代码(注意##
部分):
#define NSLog(FORMAT, ...) fprintf(stderr, "%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);