karim
karim

Reputation: 15589

NSLog inside variable arguments function

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

Upvotes: 3

Views: 2272

Answers (3)

karim
karim

Reputation: 15589

Finally, for interested people, here is my final version of logging ...

-(void) printStatus:(NSString*)status, ...
{
    va_list args;
    va_start(args, status);
    va_end(args);
    NSString * str = [[NSString alloc] initWithFormat:status arguments:args];
    DLog(@"%@", str);
    self.statusTextView.text = [_statusTextView.text stringByAppendingFormat:@"\n%@",str];
    [str release];
}

DLog is defined in my Prefix.pch file,

#ifdef DEBUG
#   define DLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#else
#    define DLog(...) /* */
#endif

Upvotes: 1

Mike Weller
Mike Weller

Reputation: 45598

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

Upvotes: 11

AMohan
AMohan

Reputation: 534

I am not able to understand the question exactly. As I understood you can use formated string

    [NSString stringWithFormat:@"this is string %@",@"String"];

Upvotes: -2

Related Questions