static const Vs extern const

前端 未结 7 2105
傲寒
傲寒 2020-12-07 19:34

I have been using static const in my header files as so:

static NSString * const myString = @\"foo\";

But have read that this is not the \'

7条回答
  •  难免孤独
    2020-12-07 19:46

    Your first variant

    static NSString * const myString = @"foo"; // In .h file, included by multiple .m files
    

    defines an myString variable locally in each "translation unit" (roughly speaking: in each .m source file) that includes the header file. All string objects have the same contents "foo", but it may be different objects so that the value of myString (the pointer to the string object) may be different in each unit.

    Your second variant

    extern NSString * const myString; // In .h file, included by multiple .m files
    NSString * const myString = @"foo"; // In one .m file only
    

    defines a single variable myString which is visible "globally".

    Example: In one class you send a notification with myString as user object. In another class, this notification is received and the user object compared to myString.

    In your first variant, the comparison must be done with isEqualToString: because the sending and the receiving class may have different pointers (both pointing to a NSString object with the contents "foo"). Therefore comparing with == may fail.

    In your second variant, there is only one myString variable, so you can compare with ==.

    So the second variant is safer in the sense that the "shared string" is the same object in each translation unit.

提交回复
热议问题