Constants in Objective-C and “duplicate symbol” linker error

孤者浪人 提交于 2020-01-10 23:23:51

问题


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?

Thanks


回答1:


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".

In case of NSInteger you can write in your every .m file:

static const NSInteger my_const = 3;

If you want globals (one constant with one value visible in every file) then write in your .h:

extern const NSInteger my_global_const;

and in your .m file you can add

const NSInteger my_global_const = 5;


来源:https://stackoverflow.com/questions/17145223/constants-in-objective-c-and-duplicate-symbol-linker-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!