开发者

Macro expansion inside NSString

开发者 https://www.devze.com 2023-04-13 03:27 出处:网络
How can I expand a macro inside NSString? I\'ve got the following code: #define MAX_MESSAGE_LENGTH 2000

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?


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";


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消