常量的另一个名字

标签 c objective-c constants

首先,我看到了this question并理解为什么以下代码不起作用。那不是我的问题。

我有一个常量,声明如下;

//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 之类的东西)我可以提供多个名称下的单个常量?

最佳答案

通常,编译器会将相同的字符串常量折叠成相同的字符串,除非您告诉它不要这样做。即使您不能用一个常量初始化另一个常量,但用相同的值初始化它们会产生相同的净效果。

//Constants.h
extern NSString * const MyConstant;
extern NSString * const MyOtherConstant;

//Constants.m
#define MyConstantValue "MyConstant"
NSString * const MyConstant = @MyConstantValue;
NSString * const MyOtherConstant = @MyConstantValue;

您将#define 隐藏在一个源文件而不是标题中。您只需更改一个地方的值。一个常量有两个名称。当然,在多个文件中定义常量的情况下,您必须让这些源文件可以访问#define。

关于常量的另一个名字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2909724/

相关文章:

c - 在 C 中释放多维数组

objective-c - (string.length, 0) 是字符串的有效范围吗?

ios - 添加一个 UIImageView 到 NavigationBar 的后面(不是背景图片)

c# - 收到 'Expression being assigned must be constant' 时

algorithm - session 调度解决方案

c - void * 指针是否用于 C 中的泛型类型?

c - 如果我运行这个程序,即使我将输入指定为 0,它也会不断获取其中的值吗?

c - 我的信号处理程序有什么问题?

ios - 我可以将一个 UIScrollView 放在另一个 UIScrollView 中吗

c++ - C++ 中的模板引用参数推导失败