How do I define a macro with variadic method in objective-C?
ios, macros, objective-c, variadic
Solution
Actually, your problem is not really related to Objective-C directly, but to C itself, as macros are plain C preprocessor directives.
In a macro, `__VA_ARGS__` represents the arguments that are placed instead of the `...`.
So in your call to `MDCLogDebug(@"Test:%@", @"Hey")`, the `format` argument is `@"Test:%@"` and `__VA_ARGS__` represents the rest of the arguments afterwards, namely simply `@"Hey"` in your case.
If you want to pass both the `@"Test:%@"` and `@"Hey"` as arguments to `logContent:`, you have to explicitly tell it so, using:
#define MDCLogDebug(format, ...) [[MDCLogController sharedController] addLogWithLevel:MDCLogLevelDebug logContent:format, __VA_ARGS__]
Note: An even better solution would be to use the `##` prefix before `__VA_ARGS__` so that the comma won't be added if `__VA_ARGS__` is empty (namely if you only pass a `format` argument but nothing afterwards, like `MDCLogDebug(@"Foo")`):
#define MDCLogDebug(format, ...) [[MDCLogController sharedController] \
addLogWithLevel:MDCLogLevelDebug \
logContent:format, ## __VA_ARGS__]
(Note: I use backslashes in this last macro definition above to allow the macro to be written on multiple lines, instead of writing it on one single big long line)
For more information, see the official GCC documentation about Variadic Macros here.
Problem
The method I am trying to call is; ``` - (void)addLogWithLevel:(MDCLogLevel)logLevel logContent:(NSString *)logContent, ... { va_list args; va_start(args, logContent); NSString *message = [[NSString alloc] initWithFormat:logContent arguments:args]; va_end(args); MDCLog *log = [MDCLog logWithContent:message content:logLevel]; [self.deviceLogs addObject:log]; } ``` I have defined the macro as; ``` #define MDCLogDebug(format, ...) [[MDCLogController sharedController] addLogWithLevel:MDCLogLevelDebug logContent:(__VA_ARGS__)]; ``` I have tried various formats of this macro, but nothing seems to work. If I am to call; ``` MDCLogDebug(@"Test:%@", @"Hey"); ``` All I see in the console is; Hey Where am I going wrong? I'm new to using Variadic methods and my C isn't so great!