常量的另一个名称
首先,我看到了这个问题并理解为什么下面的代码不起作用。这不是我的问题。
我有一个常量,其声明如下;
//Constants.h
extern NSString * const MyConstant;
//Constants.m
NSString * const MyConstant = @"MyConstant";
但是,在某些情况下,让该常量具有更具描述性的名称会更有用,例如 MyReallySpecificConstant
。我希望这样做:
//SpecificConstants.h
extern NSString * const MyReallySpecificConstant;
//SpecificConstants.m
#import "Constants.h"
NSString * const MyReallySpecificConstant = MyConstant;
显然我不能这样做(上面的链接问题对此进行了解释)。
我的问题是:
我还能如何在多个名称下提供单个常量(除了类似 #define MyReallySpecificConstant MyConstant
之类的东西)?
First off, I've seen this question and understand why the following code doesn't work. That is not my question.
I have a constant, which is declared like;
//Constants.h
extern NSString * const MyConstant;
//Constants.m
NSString * const MyConstant = @"MyConstant";
However, in certain contexts, it's more useful to have this constant have a much more descriptive name, like MyReallySpecificConstant
. I was hoping to do:
//SpecificConstants.h
extern NSString * const MyReallySpecificConstant;
//SpecificConstants.m
#import "Constants.h"
NSString * const MyReallySpecificConstant = MyConstant;
Obviously I cannot do this (which is explained in the linked question above).
My question is:
How else (besides something like #define MyReallySpecificConstant MyConstant
) can I provide a single constant under multiple names?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,编译器会将相同的字符串常量折叠到相同的字符串中,除非您告诉它不要这样做。尽管不能用一个常量初始化另一个常量,但用相同的值初始化它们将产生相同的净效果。
您可以将 #define 隐藏在一个源文件中,而不是标头中。您只需更改一处的值即可。一个常量有两个名称。当然,在多个文件中定义常量的情况下,您必须让这些源文件可以访问 #define。
In general, the compiler will fold identical string constants into the same strings unless you tell it not to. Even though you cannot initialize one constant with another, initializing them both with the same value will have the same net effect.
You hide the #define in one source file instead of in a header. You only have to change the value in one place. You have two names for one constant. Of course, in your scenario with constants defined in multiple files, you would have to have the #define accessible to those source files.
我对你的问题的第一反应是反过来问 - 你想要在多个名称下使用一个常量,这是否表明常量的名称首先需要重新考虑?
My first reaction to your question was a question in return - Is the fact that you want to have a constant under multiple names, an indicator that the name of the constant needs rethinking in the first place?
在代码中分配字符串常量:
如果编译器没有保护它们不被修改,那么这是一个缺点。然而,初始化非常灵活,您也许可以改进其他代码。您还可以保证字符串的地址不同,无论编译器是否决定本周执行折叠操作。
Assign your string constants in code:
One downside if that they are not protected by the compiler against modification. However the initialization is very flexible and you maybe be able to improve other code. You also guarantee different addresses for your strings, whether or not the compiler decides that folding is what it does this week.