g.revolution
g.revolution

Reputation: 12262

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 ')'"

Upvotes: 3

Views: 5243

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

You cannot do it with variables: the reason it works with string literals is that when you write several literals separated by whitespace, the compiler combines them in a single string literals for you.

The solution that you have (with the format string for three %@ specifiers) is a good one. You can also format the three values in a similar way.

Upvotes: 6

The Kraken
The Kraken

Reputation: 3158

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).

Upvotes: 8

Related Questions