iOS #define 或全局字符串的静态常量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18283988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS #define or static const for global strings
提问by user1802143
I have a constants.h file that declares a bunch of strings that I use throughout my app. I only have strings and nothing else. Am I supposed to use #define or static NSString const? #define works but I hear its not best practice.
我有一个 constants.h 文件,它声明了我在整个应用程序中使用的一堆字符串。我只有字符串,没有别的。我应该使用 #define 还是 static NSString const?#define 有效,但我听说它不是最佳实践。
回答by Bruno Koga
The #define
is a pre-processor macro. That means that it basically goes through your code and replace your macro with what you've defined.
的#define
是预处理器宏。这意味着它基本上会遍历您的代码并用您定义的内容替换您的宏。
If you use a const, it's going to be a pointer to the string in memory. It's way more efficient than having the same string being allocated wherever/whenever it is used.
如果使用 const,它将是指向内存中字符串的指针。它比在任何地方/任何时候使用相同的字符串都分配更有效。
To do that, you'll need both .h and .m files. Your .h file will look something like:
为此,您需要 .h 和 .m 文件。您的 .h 文件将类似于:
extern NSString * const YOUR_STRING;
And your .m file:
还有你的 .m 文件:
NSString * const YOUR_STRING = @"your string";