質問

I want to be able to wrap all calls to NSLog in my Class so I can have a single place to enable/disable logging.

I can't figure out how to accept variable numbers of arguments to my method and then hand them on to NSLog.

Examples, please.

役に立ちましたか?

解決

for a logger I'd just go with a macro

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

#else
#define DebugLog(...)

#endif

BUT

if you want to work with variable arguments:

declare your method as so it takes a variable number of arguments

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

use the va_* C functions to interact with the variable arguments

  • va_start - Initializes a va_list
  • va_arg - Fetches the next argument out of the list.
  • va_end - Releases any memory by the list of vas

DEMO for the logging

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

他のヒント

I use a handy set of Macros from 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)

This doesn't need any configuration as DEBUG and RELEASE are defined by Xcode as standard. This provides:

  • DLog() Only emits an NSLog in DEBUG
  • ALog() Throws an assertion with the message in DEBUG, and emits an NSLog in RELEASE
  • ZAssert() Throws an Assertion if the condition fails in DEBUG, and emits an NSLog if the condition fails in RELEASE.

And the logs are pretty printed - showing the class and method where the log is emitted.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top