Preprocessor macro value to Objective-C string literal

前端 未结 4 657
礼貌的吻别
礼貌的吻别 2021-02-01 04:18

I have a preprocessor macro defined in build settings

FOO=BAR

That value I want to massage into an Objective-C string literal that can be passe

相关标签:
4条回答
  • 2021-02-01 04:47

    What error are you seeing exactly? This type of thing does work as you expect:

    #define kMyString @"MyString"
    
    [NSString stringWithFormat:@"macro: %@", kMyString];
    
    0 讨论(0)
  • 2021-02-01 04:54

    You need to define preprocessor macro like,

    FOO=\@\"BAR\"
    

    And use code side like,

    [NSString stringWithFormat:@"macro: %@", FOO];
    
    0 讨论(0)
  • 2021-02-01 04:58

    Here's a modified version of Adam Rosenfield's answer with clearer semantics:

    #define NSStringize_helper(x) #x
    #define NSStringize(x) @NSStringize_helper(x)
    

    I use it to replace code like this:

    case OneEnumValue: name = @"OneEnumValue"; break;
    case AnotherEnumValue: name = @"AnotherEnumValue"; break;
    

    with this:

    #define case_for_type(type) case type: name = NSStringize(type); break
    
    case_for_type(OneEnumValue);
    case_for_type(AnotherEnumValue);
    
    0 讨论(0)
  • 2021-02-01 04:59

    Use the stringizing operator # to make a C string out of the symbol. However, due to a quirk of the preprocessor, you need to use two extra layers of macros:

    #define FOO BAR
    #define STRINGIZE(x) #x
    #define STRINGIZE2(x) STRINGIZE(x)
    #define FOOLITERAL @ STRINGIZE2(FOO)
    // FOOLITERAL now expands to @"BAR" 
    

    The reason for the extra layers is that the stringizing operator can only be used on the arguments of the macro, not on other tokens. Secondly, if an argument of a macro has the stringizing operator applied to it in the body of the macro, then that argument is not expanded as another macro. So, to ensure that FOO gets expanded, we wrap in another macro, so that when STRINGIZE2 gets expanded, it also expands FOO because the stringizing operator does not appear in that macro's body.

    0 讨论(0)
提交回复
热议问题