When to use static string vs. #define

前端 未结 6 1885
-上瘾入骨i
-上瘾入骨i 2021-01-30 10:49

I am a little confused as to when it\'s best to use:

static NSString *AppQuitGracefullyKey = @\"AppQuitGracefully\";

instead of



        
6条回答
  •  渐次进展
    2021-01-30 11:20

    I actually would recommend neither, you should use extern instead. Objective-c already defines FOUNDATION_EXPORT which is more portable than extern, so a global NSString instance would look something like this:

    .h

    FOUNDATION_EXPORT NSString * const AppQuitGracefullyKey;
    

    .m

    NSString * const AppQuitGracefullyKey = @"AppQuitGracefully";
    

    I usually put these in declaration files (such as MyProjectDecl.h) and import whenever I need.

    There are a few differences to these approaches:

    • #define has several downsides, such as not being type safe. It is true that there are workarounds for that (such as #define ((int)1)) but what's the point? And besides, there are debugging disadvantages to that approach. Compilers prefer constants. See this discussion.
    • static globals are visible in the file they are declared.
    • extern makes the variable visible to all files. That contrasts with static.

    Static and extern differ in visibility. It's also notable that neither of these approaches duplicates the string (not even #define) as the compiler uses String Interning to prevent that. In this NSHipster post they show proof:

    NSString *a = @"Hello";
    NSString *b = @"Hello";
    BOOL wtf = (a == b); // YES
    

    The operator == returns YES only if the two variables point at the same instance. And as you can see, it does.

    The conclusion is: use FOUNDATION_EXPORT for global constants. It's debug friendly and will be visible allover your project.

提交回复
热议问题