在Objective-C中包含对NSLog的调用

时间:2013-09-23 15:42:15

标签: objective-c nslog variadic-functions

我希望能够在我的类中包含对NSLog的所有调用,这样我就可以在一个地方启用/禁用日志记录。

我无法弄清楚如何接受我方法的可变数量的参数,然后将它们交给NSLog。

请举例。

2 个答案:

答案 0 :(得分:3)

对于记录器我只需要使用宏

#if DEBUG
#warning LOGGING ENABLED
#define DebugLog(fmt, ...) NSLog((@"%s " fmt), __PRETTY_FUNCTION__, ##__VA_ARGS__)

#else
#define DebugLog(...)

#endif

BUT

如果你想使用变量参数:

声明你的方法,因为它需要可变数量的参数

+ (id)stringWithFormat:(NSString *)format, ...;

使用va_ * C函数与变量参数进行交互

  • va_start - 初始化va_list
  • va_arg - 从列表中获取下一个参数。
  • va_end - 通过vas列表释放所有内存

记录的DEMO

#import <Foundation/Foundation.h>

#define DEBUG 1

#if DEBUG
#warning LOGGING ENABLED
#define DebugLog(fmt, ...) NSLog((@"%s " fmt), __PRETTY_FUNCTION__, ##__VA_ARGS__)

#else
#define DebugLog(...)

#endif

int main(int argc, char *argv[]) {
    @autoreleasepool {
                    id v = @1;
        DebugLog(@"bla: %@", v);        
    }
}

答案 1 :(得分:2)

我使用Marcus Zarra中的一组方便的宏:

#ifdef DEBUG
  #define DLog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
  #define ALog(...) [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__]
#else
  #define DLog(...) do { } while (0)
  #ifndef NS_BLOCK_ASSERTIONS
    #define NS_BLOCK_ASSERTIONS
  #endif
  #define ALog(...) NSLog(@"%s %@", __PRETTY_FUNCTION__, [NSString stringWithFormat:__VA_ARGS__])
#endif

#define ZAssert(condition, ...) do { if (!(condition)) { ALog(__VA_ARGS__); }} while(0)

这不需要任何配置,因为DEBUG和RELEASE由Xcode定义为标准。这提供了:

  • DLog()仅在DEBUG中发出NSLog
  • ALog()在DEBUG中使用消息抛出断言,并在RELEASE中发出NSLog
  • ZAssert()如果条件在DEBUG中失败则抛出断言,如果条件在RELEASE中失败则抛出NSLog。

日志打印得非常漂亮 - 显示了发布日志的类和方法。