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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…