Search code examples
objective-cnslogvariadic-functions

Wrap calls to NSLog in Objective-C


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.


Solution

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