Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 665
tadman Avatar asked Jun 06 '12 19:06

tadman


People also ask

How do you declare a string in Objective C?

NSString *myNSString = [NSString stringWithFormat:@"test"]; NSString *myRetainedNSString = [[NSString alloc] initWithFormat:@"test"]; Or if you need an editable string: NSMutableString *myMutableString = [NSMutableString stringWithFormat:@"test"];

What is NSString?

A static, plain-text Unicode string object which you use when you need reference semantics or other Foundation-specific behavior.

What does an Objective C string literal look like?

eg: const int age = 10; A string literal is a expression like @"" . The compiler will replace this with an instance of NSString . A string constant is a read-only pointer to NSString .


1 Answers

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

like image 66
Oleg Trakhman Avatar answered Oct 06 '22 16:10

Oleg Trakhman