Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c function declaration in xcode / to replace NSLog with something that behaves differently in debug and release

It is a rather silly question! but in the following function how do you use the remaining arguments passed in:

void NSLog(NSString *format, ...)
{
    //here I can use "format" but how can I use the remaining arguments?
}

It is hard to find the answer to this question because I cant search for "..." ?! By the way that is how NSLog works but I put it here just as an example my question has nothing to do with NSLog.

like image 958
Ali Avatar asked Dec 17 '22 12:12

Ali


2 Answers

Use a variable argument list:

void NSLog(NSString *format, ...)
{
    va_list ap;
    va_start(ap, format);

    while( (value = va_arg(args, NSString *) ){
        // Do something with value. This is assuming they are all strings
    }

    // or pass entire list to another function
    NSLog_VA( format, ap );

    va_end(ap);
}

void NSLog_VA( NSString * format, va_list args )
{
    // do something with va_list here
}

Edit: Since you want a debug only log:

#ifdef DEBUG 
#define DebugOnly_Log(format, args...) NSLog(format, ##args) 
#else 
#define DebugOnly_Log(format, args...) // defined to nothing
#endif 
like image 96
pohsyb Avatar answered Dec 19 '22 01:12

pohsyb


Have a look at stdarg.h

It might look a bit like -

void NSLog(NSString *format, ...)
{

  va_list args;
  va_start(args,format);
  vprintf([format cString], args);
  va_end(args);
}
like image 36
Nick Van Brunt Avatar answered Dec 19 '22 00:12

Nick Van Brunt