Search code examples
iosobjective-cmacosnslog

how to put NSString in NSLog with multiple arguments


when i try to use NSLog like:

NSLog(@"one" @"two" @"three");

this works and prints onetwothree in console. but when i try to use like this

NSString *s = [NSString stringWithFormat:@"three"];  
NSLog(@"one" @"two" s);

the above doesnt work and i get a compile time error that "Expected ')'". I am not sure what to do.

any help?

P.S. I am trying to use XcodeColors and I have to give arguments to NSLog like above. so don't answer that use it like below. I know this works. but I have to pass arguments to NSLog like above.

NSString *s = [NSString stringWithFormat:@"%@ %@ %@", @"one", @"two", @"three"];  
NSLog(s, nil);

Edit:

I can use NSLog like this to get my desired result:

NSString *s = @"ss";
NSLog(@"one" @"two" @"%@",s);

that leads to my another question. I want to make a macro for NSLog. the macro looks like:

LOG_X(val) NSLog(@"xx" @"yy" @"%@",val @"zz")

Now when the following works:

LOG_X(@"one")
LOG_X(@"one" @"two" @"three")

but following does not work

NSString *s = @"one two three";
LOG_X(s);

it gives me the same error "Expected ')'"


Solution

  • If you want to print out the contents of an NSString variable in NSLog, you need to treat it like a formatted string.

    So instead of:

    NSLog(@"one" @"two" s);

    Use:

    NSLog(@"one" @"two" @"%@", s);

    ADDITION:

    You must insert the comma and val at the end of the macro. It should look like:

    #define LOG_X(val) NSLog(@"xx" @"yy" @"%@" @"zz", val).