Global constants in Objective-C

前端 未结 3 2033
春和景丽
春和景丽 2021-01-05 02:54

I\'ve a file called Constants.h:

extern NSString * const BASE_URL;

and Constants.m:

#ifde         


        
相关标签:
3条回答
  • 2021-01-05 03:23

    Solution A:

    Personally, I would just use a function for ANOTHER_URL.

    Solution B:

    If you really want a constant: You should be able to use cstring concatenation rules via #define, then pipe that through CFSTR():

    // defs.h
    extern NSString * const BASE_URL;
    extern NSString * const ANOTHER_URL;
    
    // defs.m
    
    #ifdef DEBUG
    #define DEF_BASE_URL "http://www.example.org"
    #else
    #define DEF_BASE_URL "http://localhost"
    #endif
    
    NSString * const BASE_URL = (NSString*)CFSTR(DEF_BASE_URL);
    NSString * const ANOTHER_URL = (NSString*)CFSTR(DEF_BASE_URL "/path/");
    

    Solution C:

    If you want to create just one via initialization, you can also accomplish a function/method local static in C++/ObjC++ translations (then use C or ObjC visibility, where needed):

    NSString * URL() {
      static NSString * const ANOTHER_URL = [NSString stringWithFormat:@"%@%@", BASE_URL, @"/path/"];
      return ANOTHER_URL;
    }
    
    0 讨论(0)
  • 2021-01-05 03:32

    Firstly, you can tell Xcode to set some preprocessor macros for debug builds. Use the build option 'preprocessor macros'.

    For your second question, you can't call an objective-C method to fill a constant, because that stuff isn't available at compile-time. Your best option is to define the global variable, then give it a value in the class 'initialize' method.

    static NSString * ANOTHER_URL;
    
    + initialize {
        ANOTHER_URL = [NSString stringWithFormat:@"%@%@", BASE_URL, @"/path/"];
    }
    

    initialize is called before your first instance of the class is created, so it's safe. You'll have to drop the const keyword, but I'm sure you can trust yourself! ;)

    0 讨论(0)
  • 2021-01-05 03:44

    #define DEBUG 1 or 0 to disable.

    The error is because you are calling a method of NSString while its a compile constant. In other words you are telling the compiler something it simply can't handle. You will need to initialize such a dynamic link on launch, the compiler can't do this for you.

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