静态常量与外部常量 [英] static const Vs extern const

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

问题描述

我一直在头文件中使用静态常量,如下所示:

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 源文件中)包括头文件.所有字符串对象都具有相同的内容foo",但它可能是不同的对象,因此 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.

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

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