NSLog inside variable arguments function

ios, iphone, nslog, objective-c, variadic-functions

Solution

You need to work with C's varargs types and the `NSLogv` macro:

-(void)printStatus:(NSString*)status, ...
{
    va_list args;
    va_start(args, status);
    NSLogv(status, args);
    va_end(args);
}

This assumes the `status` argument is a format string followed by its arguments.

If you want to create an `NSString` from the format string and arguments (for updating your GUI) you can do this in addition to `NSLogv`:

NSLogv(status, args);
NSString *message = [[NSString alloc] initWithFormat:status arguments:args];
// ... log to GUI

Problem

I do not have clear idea about objective c variable argument function. I want to write a function which will take a nlsog type parameter but sometime I shall use NSLog inside that function. How can I do that? ``` -(void) printStatus:(NSString*)status, ... { // I want use use NSLog with all these parameter here. // some gui logging also happens here } ``` Calls will be like this, ``` [self printStatus:@"status"]; ``` or ``` [self printStatus:@"Staus: %@", someObject]; ``` Instead of using NSLog, I want to use printStatus. When I need to switch the console logging to a GUI logging, I can do it only changing to the printStatus function, not changing all places inside my code. Or use DLog as I am using here, ``` #ifdef DEBUG # define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #else # define DLog(...) /* */ #endif ```

Original source