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

I am trying to create a macro definition that can emit C ++ or Objective-C depending on the context, but cannot easily build an NSString inside a macro. The C ++ version is simple because it uses regular strings, but creating what emits an NSString turns out to be difficult:

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

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

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

Instead, I get an error that prevents compilation:

 Pasting formed '@"x"', an invalid preprocessing token 
+6
source share
3 answers
 NSString *x = @"text"; 

Equally:

 NSString *x = CFSTR("text"); 

PS NSString * and CFStringRef and __CFString *, as well as NSCFStringRef - all the same: Unlimited bridge types

+5
source

You cannot use ## to concatenate elements unless they form a valid preprocessing token together, but you can call the NSString constructor, which takes a C string, for example:

 #define FOO(x) [NSString stringWithUTF8String:(x)] 
+3
source

Um, why not:

 #define FOO(x) bar(@x) 

?

There is no need to insert or overlay tokens or anything strange. You just need the @ sign in the argument list at the substitution point. So just do it.

+3
source

Source: https://habr.com/ru/post/917480/


All Articles