Reputation: 29886
I have seen examples on wrapping NSLog but am not 100% sure on the details.
e.g. #define debugLog(fmt,...) NSLog(@"%@",[NSString stringWithFormat:(fmt), ##__VA_ARGS__]);
What exactly are the arguments here?
If I wanted to add a constant string to a log such as
- (void) logMessage:(NSString *) message ofType:(NSString *) type
{
NSLog(@"%@ - %@", type, message);
}
how would I create this in a #define macro?
Upvotes: 2
Views: 909
Reputation: 43498
debugLog
is a variadic macro (one that takes a variable number of arguments). The particular macro calls NSLog
with 2 arguments, the first being a format string (@"%@"
), and the second being an autoreleased string returned by stringWithFormat
which takes the passed format string plus the variadic arguments of the macro.
__VA_ARGS__
is the way to refer to the variable argument list within the macro. It corresponds to the ...
in the parameter list.
Instead of your logMessage
method, you could use the debugLog
macro to achieve the same result:
debugLog("%@ - %@", type, message);
The macro itself seems a bit pointless though, since it is only wrapping NSLog
without adding anything else.
If you want a macro that corresponds directly to logMessage
, then you don't have to deal with a variadic list at all:
#define logMessageAsMacro(message, type) NSLog(@"%@ - %@", message, type)
You'll have to be careful about whether both of the arguments are NSString
's, since macros are type-unsafe.
Upvotes: 4