Constants in Objective-C

后端 未结 14 1285
广开言路
广开言路 2020-11-21 22:10

I\'m developing a Cocoa application, and I\'m using constant NSStrings as ways to store key names for my preferences.

I understand this is a good idea b

14条回答
  •  感动是毒
    2020-11-21 23:00

    A slight modification of the suggestion of @Krizz, so that it works properly if the constants header file is to be included in the PCH, which is rather normal. Since the original is imported into the PCH, it won't reload it into the .m file and thus you get no symbols and the linker is unhappy.

    However, the following modification allows it to work. It's a bit convoluted, but it works.

    You'll need 3 files, .h file which has the constant definitions, the .h file and the .m file, I'll use ConstantList.h, Constants.h and Constants.m, respectively. the contents of Constants.h are simply:

    // Constants.h
    #define STR_CONST(name, value) extern NSString* const name
    #include "ConstantList.h"
    

    and the Constants.m file looks like:

    // Constants.m
    #ifdef STR_CONST
        #undef STR_CONST
    #endif
    #define STR_CONST(name, value) NSString* const name = @ value
    #include "ConstantList.h"
    

    Finally, the ConstantList.h file has the actual declarations in it and that is all:

    // ConstantList.h
    STR_CONST(kMyConstant, "Value");
    …
    

    A couple of things to note:

    1. I had to redefine the macro in the .m file after #undefing it for the macro to be used.

    2. I also had to use #include instead of #import for this to work properly and avoid the compiler seeing the previously precompiled values.

    3. This will require a recompile of your PCH (and probably the entire project) whenever any values are changed, which is not the case if they are separated (and duplicated) as normal.

    Hope that is helpful for someone.

提交回复
热议问题