The Tosters The Tosters - 1 year ago 180
Objective-C Question

Concat two macros in Objective-C

I'm trying to concatenate two values each defined as macro. At this moment I've:

#define VAL1 @"im/"
#define VAL2 @"test"
#define GLUE_IN(x,y) (x ## y)
#define GLUE(x,y) GLUE_IN(x,y)

when I use it in code:

[array addObject:GLUE(VAL1, VAL2)];

it produces me an error: Pasting formed '"im/"@', an invalid preprocessing token

I'm aware that it may be solved by:

#define GLUE(x,y) [NSString stringWithFormat:@"%@%@",x,y]

however I'm curious is it possible to achieve this same result using preprocessor?

Answer Source

## concatenates tokens, not strings, which causes an invalid resulting token, and in this case is entirely un-necessary since @"im/" @"test" - being compile time string constants - will be appended anyway. Just do;

#define GLUE_IN(x,y) (x y)

...which will result in

[array addObject:@"im/" @"test"]

...and things should work well.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download