问题描述
我已经在一些不同的类中声明了一个同名的常量,在它们的 .m
文件中,这样:
I've declared a constant with the same name in some different classes, in their .m
file, this way:
@implementation MyViewController
const NSInteger numberOfItems = 6;
...
@end
但在尝试构建项目时出现重复符号"错误.我发现了几篇关于外部或全局常量的帖子处理这个问题,但我想要的只是将一些常量声明为他们的类私有,我该怎么做?
But I get a "duplicate symbol" error when trying to build the project. I've found several posts dealing with this issue regarding extern or global constants, but what I'd want is just declaring some constants private to their class, how can I do that?
谢谢
推荐答案
如果您只想在一个 .m
文件中使用常量,则将其声明为 static
.例如:static NSString * const CONSTANT_STRING = @"Constant I am"
.
If you want to use constant only in one .m
file then declare it as static
.For example:static NSString * const CONSTANT_STRING = @"Constant I am"
.
如果是 NSInteger
,您可以在每个 .m
文件中写入:
In case of NSInteger
you can write in your every .m
file:
static const NSInteger my_const = 3;
如果你想要全局变量(一个常量,每个文件中都有一个可见的值)然后写在你的 .h
:
If you want globals (one constant with one value visible in every file) then write in your .h
:
extern const NSInteger my_global_const;
您可以在 .m
文件中添加
and in your .m
file you can add
const NSInteger my_global_const = 5;
这篇关于Objective-C 中的常量和“重复符号"链接器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!