When to use static string vs. #define

前端 未结 6 1901
-上瘾入骨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:02

    USING #define :

    you can't debug the value of identifier

    work with #define and other macros is a job of Pre-Processor, When you hit Build/Run first it will preprocess the source code, it will work with all the macros(starting with symbol #),

    Suppose, you have created,

    #define LanguageTypeEnglish @"en"
    

    and used this at 2 places in your code.

    NSString *language = LanguageTypeEnglish;
    NSString *languageCode = LanguageTypeEnglish;
    

    it will replace "LanguageTypeEnglish" with @"en", at all places. So 2 copies of @"en" will be generated. i.e

    NSString *language = @"en";
    NSString *languageCode = @"en";
    

    Remember, till this process, compiler is not in picture.

    After preprocessing all the macros, complier comes in picture, and it will get input code like this,

    NSString *language = @"en";
    NSString *languageCode = @"en";
    

    and compile it.

    USING static :

    it respects scope and is type-safe. you can debug the value of identifier

    During compilation process if compiler found,

    static NSString *LanguageTypeRussian = @"ru";
    

    then it will check if the variable with the same name stored previously, if yes, it will only pass the pointer of that variable, if no, it will create that variable and pass it's pointer, next time onwards it will only pass the pointer of the same.

    So using static, only one copy of variable is generated within the scope.

提交回复
热议问题