可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 'safe' or correct way of doing this. Apparently, if I want my const strings to be accessed from another class, I should be declaring the string in my .h as:
extern NSString * const myString;
Then in my .m file:
NSString * const myString = @"foo";
Is this correct? If so, what is the reason not to declare it as static directly in my .h file? It works perfectly fine, and I can not see any 'safety' issues around this. It is a const, so therefore it can not be changed from outside and its something I intentionally need accessed outside of the class. The only other thing I can think of is that to hide the value of the string?
回答1:
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.
回答2:
There is no reason that I know of, for declaring anything as external in Objective-C, while you use Objective-C only in your project.
I could think of reasons when you mix it with C or assembler modules etc.
However, extern
has the advantage that the constant will really exist only ones in the whole project, if it is that what you want to achieve, if you really need to save on these 20 or so bytes.
But that carries the risk of conflicting names. Other libraries may have declared their own externals using the same name. And the linker would care for them using the very same space in memory, although they may be of different types.
And yes, the extern
declaration in the header should be accompanied by a corresponding definition in the .m file. I am not sure but I think you could assign @"foo" in the .h file already.
You could even declare it outside of @interface/@implementation-@end blocks. (Never tried that myself). In that case the variable would be global and accessible from everywhere even without the extern
keyword. On compile time the compiler would complain about accessing them when he does not see its declaration within the chain of #include statements. But academically, one single .m file could contain two or more classes (which I clearly do not advise) and then the variable would be accessible from both classes although it belongs to none of them.
In the end, OjbC is just an add-on to ANSI C.
However, there is no point in making them static. These constants are static anyway. They are constants. The purpose of a static variable within a class or even method is it's scope (visibility) is limited to that class but there is only one instance on runtime that is shared by all instances of the class.
Example:
@implementation AClass : NSObject
static NSString *someString
- (void) setString:(NSString*) aString{
someString = aString;
}
- (NSString*) getString (){
return someString;
}
... and somewhere else:
AClass * a = [[AClass alloc] init];
AClass * b = [[AClass alloc] init];
[a setString:@"Me"];
[b setString;@"You"];
NSLog (@"String of a: ", [a getString]);
would print out You
but not Me
If that is what you want, and only then, use static.
Using simple preprocessor macros (which I prefer, but I am kinda oldschool here) has the disadvantage that these strings would be copied into the binary each time when the macro is used. Apparently that is not an option for you anyway because you did not even asked for them.
However, for most usages preprocessor macros in commonly shared .h files would do the trick of managing constants across classes.
回答3:
Using static NSString* const myString = @"foo";
in a header file means that each translation unit gets a separate myString
variable. I think the linker may consolidate these, but I wouldn't count on it. That means that code which compares a string it has received using if (someString == myString) ...
might get false even if the caller passed myString
in, if the caller were from a different translation unit. (Of course, code should use -isEqualToString:
instead of ==
, but with a properly-declared string constant the latter may be workable.)
回答4:
The advantage of the extern way is described in other answers.
One possible advantage of the static way if the variable were not an object (NSString
in your case) but of a primitive type (like an integer) is that, the compiler is able to optimize the access to the constant:
When you declare a const in your program,
int const x = 2;
Compiler can optimize away this const by not providing storage to this variable rather add it in symbol table. So, subsequent read just need indirection into the symbol table rather than instructions to fetch value from memory.
Taken from this answer.
回答5:
But have read that this is not the 'safe' or correct wary of doing this.
It is safe, unless the program is multi-threaded. In that case, it is not safe unless you protect the global variable with a mutex.
It is however not correct. NSString * const myString
means a constant pointer to (non-constant) data. Most likely, you want the variable itself to be constant: const NSString* myString
.
Apparently if i want my const strings to be accessed from another class i should be declaring the string in my .h as: extern
...
Correct. Note that extern
is acceptable for constants only. It is not acceptable for non-constant variables: global variables are considered to be very bad practice.
if so what is the reason to not just use declare it as static directly in my .h file as it works perfectly fine
The only reason why you would ever want to declare it as static is because you want to limit the scope of the variable to the local .c file, in other words private encapsulation. Therefore it does not ever make sense to declare static variables in a .h file.
It is a const so therefore can not be changed from outside
It can be changed, because it is not const, see my first remark.
Generally, don't do things like this. All of the above fiddling suggests that you have flaws in your very program design, that need to be fixed. You need to design your program in an object-oriented manner, so that every code module is autonomous and doesn't know or care about anything except it's designated task.
回答6:
When it comes to storage classes, static means one of two things.
A static variable inside a method or function retains its value
between invocations.
A static variable declared globally can be called
by any function or method, so long as those functions appear in the
same file as the static variable. The same goes for static functions.
Whereas static makes functions and variables globally visible within a particular file, extern makes them visible globally to all files.
Any time your application uses a string constant with a non-linguistic value in a public interface, it should declare it as an external string constant.
The pattern is to declare an extern NSString * const in a public header, and define that NSString * const in the implementation.
Source: nshipster.com/c-storage-classes
回答7:
#define myString @"foo"
There is example why:
You will be able concatenate strings in compile time:
NSLog(@"%@", @"Say hello to " myString);
will output: Say hello to foo