静态常量VS常量的extern [英] static const Vs extern const

查看:106
本文介绍了静态常量VS常量的extern的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用静态常量在我的头文件,像这样:

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

static NSString * const myString = @"foo";

但已阅读,这是不是这样做的安全或正确的方法。很显然,如果我想从另一个类来访问我的const字符串,我要声明的字符串在我的.h为:

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;

然后在我的.m文件:

Then in my .m file:

NSString * const myString = @"foo";

这是正确的?如果是这样,究竟是什么原因没有在我.h文件中直接声明为静态的?这工作完全正常,而且我看不到解决这个任何安全的问题。这是一个常数,因此,它不能从它的东西,我故意所需要的类之外访问之外,并进行更改。我能想到的唯一的另一件事是隐藏的字符串值?

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?

推荐答案

您第一个变种

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

每一个翻译单位本地定义了一个的myString 变量的(粗略地讲:在每个.M源文件)
包含头文件。所有的字符串对象具有相同内容的富,
但它可能是不同的对象,使的myString 的值(指针的字符串对象)
可以在每个单元中不同。

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.

您第二个变种

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

定义的的变量的myString 这是明显的全球。

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

示例:在一个类中,你发送带有的myString 的通知为用户对象。
在另一类,收到此通知,用户对象相比,的myString

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.

在你的第一个变型,比较的必须做到的有 isEqualToString:,因为
发送和接收的类可以具有不同的指针(两者指向一个
的NSString 对象,内容为foo)。因此,使用 ==比较可能会失败。

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.

在你的第二个变型,只有一个的myString 变量,所以你可以用比较 ==

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.

这篇关于静态常量VS常量的extern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆