tadman
tadman

Reputation: 211580

Objective-C Preprocessor Definition, Dynamic C-String to NSString Declaration

I'm trying to create a macro definition that can emit C++ or Objective-C depending on context but can't seem to construct an NSString inside a macro easily. The C++ version is simple because it uses regular strings, but making one that emits NSString is proving tricky:

#define FOO(x) bar(@##x)

The intended result is to convert a string argument to an NSString argument by prefixing with @:

FOO("x")
// => bar(@"x")

What I get instead is an error that prevents compilation:

Pasting formed '@"x"', an invalid preprocessing token

Upvotes: 6

Views: 1221

Answers (3)

Ken Thomases
Ken Thomases

Reputation: 90551

Um, why not this:

#define FOO(x) bar(@x)

?

There's no need to do token pasting or stringifying or anything weird. You just want what's in the argument list at the substitution point to be preceded by an @ sign. So just do that.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

You cannot use ## to concatenate elements unless they form a valid preprocessing token together, but you can call NSString's constructor that takes a C string, like this:

#define FOO(x) [NSString stringWithUTF8String:(x)]

Upvotes: 3

Oleg Trakhman
Oleg Trakhman

Reputation: 2082

NSString *x = @"text";

Equals:

NSString *x = CFSTR("text");

PS NSString* and CFStringRef and __CFString* and also NSCFStringRef are all the same: Toll-Free Bridged Types

Upvotes: 5

Related Questions