Search code examples
objective-cmacros

Objective-c Macro Language detection


I want a macro with the language in in. Currently the code is:

#define APP_LOCALE_X @([[[NSLocale preferredLanguages] objectAtIndex:0] isEqualToString:@"nl_NL"]);
#ifdef APP_LOCALE_X
    #define APP_LOCALE @"&locale=nl_NL"
#else
    #define APP_LOCALE @"&locale=en_US"
#endif

Logically this will not work since #ifdef sees the macro defined. I can't seem to wrap my head around the Macro logic.

The other option would be to have a macro with the APP_LOCALE_X and a string. Like this: Obviously this is pseudo code:

#define APP_LOCALE_X @([[NSLocale preferredLanguages] objectAtIndex:0]) == "nl_NL");
#define APP_LOCALE @"&locale="APP_LOCALE_X

Solution

  • You can use ternary operator inside macro for condition instead of #ifdef:

    #define APP_LOCALE ([[[NSLocale preferredLanguages] objectAtIndex:0] isEqualToString:@"nl_NL"] ? @"&locale=nl_NL" : @"&locale=en_US")
    

    If you want to have boolean value extracted to a separate variable you can do it the following way:

    #define APP_LOCALE_X [[[NSLocale preferredLanguages] objectAtIndex:0] isEqualToString:@"nl_NL"]
    #define APP_LOCALE (APP_LOCALE_X ? @"&locale=nl_NL" : @"&locale=en_US")
    

    Please note that in your example you placed semicolon ; after #define statement, you should not place it there, as it will be inserted when expanding macro.