dmitry747
dmitry747

Reputation: 593

Macro expansion inside NSString

How can I expand a macro inside NSString? I've got the following code:

#define MAX_MESSAGE_LENGTH 2000

NSString *alertTxt = @"Your message exceeded MAX_MESSAGE_LENGTH characters";

As you can predict I get "Your message exceeded MAX_MESSAGE_LENGTH characters" instead of "Your message exceeded 2000 characters". Is there a way to get my MAX_MESSAGE_LENGTH expanded in the string?

Upvotes: 0

Views: 1568

Answers (2)

Mats
Mats

Reputation: 8628

NSStrings works like C strings. I.e. you can concatenate string constants by writing them next to each other.

/* nested macro to get the value of the macro, not the macro name */
#define MACRO_VALUE_TO_STRING_( m ) #m
#define MACRO_VALUE_TO_STRING( m ) MACRO_VALUE_TO_STRING_( m )

#define MAX_MESSAGE_LENGTH 2000
NSString *alertTxt = @"Your message exceeded "
                      MACRO_VALUE_TO_STRING(MAX_MESSAGE_LENGTH)
                      " characters";

Upvotes: 8

fearmint
fearmint

Reputation: 5334

You can use stringWithFormat: like this:

NSString *alertTxt = [NSString stringWithFormat:@"Your message exceeded %i characters", MAX_MESSAGE_LENGTH];

This uses the same placeholders %@, %i, etc. as NSLog.

Upvotes: 1

Related Questions