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



我希望能够将 NSLog 的所有调用包装在我的类中,以便我可以有一个地方启用/禁用日志记录。

我不知道如何接受可变数量的参数到我的方法,然后将它们交给 NSLog。

请举例。

对于记录器,我只会使用宏

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

如果要使用变量参数:

将方法声明为需要可变数量的参数

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

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

  • va_start - 初始化va_list
  • va_arg - 从列表中获取下一个参数。
  • va_end - 通过 vas 列表释放任何内存
<小时 />

日志记录演示

#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);        
    }
}

我使用了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。

日志打印得很漂亮 - 显示发出日志的类和方法。

最新更新