C in xcode / to replace NSLog with something that behaves differently in debugging and release

This is a pretty dumb question! but in the following function, how do you use the remaining arguments passed to:

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

It is difficult to find the answer to this question, because I can not find the "..." ?! By the way, how NSLog works, but I put it here as an example, my question has nothing to do with NSLog.

+4
source share
4 answers

Use a list of variables:

 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 only need a debug log:

 #ifdef DEBUG #define DebugOnly_Log(format, args...) NSLog(format, ##args) #else #define DebugOnly_Log(format, args...) // defined to nothing #endif 
+5
source

Take a look at stdarg.h

It may look a bit -

 void NSLog(NSString *format, ...) { va_list args; va_start(args,format); vprintf([format cString], args); va_end(args); } 
+4
source

This is called a variational function , and you can access your arguments using macros in stdarg.h .

+3
source

OK, thanks to everyone, I followed the direction that you gave me, and this solution: As far as I understand, there is no general / portable solution to the problem of getting a variable number of arguments and passing them to another function that takes a variable number of arguments (as http mentioned to it : //c-faq.com/varargs/handoff.html ).

But I wanted to implement an alternative to NSLog (I call it AliLog), which behaves like NSLog during debugging, but does nothing for the release version (or does something other than writing to the console).

here is my solution:

 void AliLog(NSString *format, ...) { #ifdef DEBUG va_list args; va_start(args, format); NSLogv(format, args); va_end(args); #else // do nothing! or something that makes sense in a release version #endif } 

The magic is in NSLogv here.

0
source

All Articles