iOS #define或全局字符串的静态const [英] iOS #define or static const for global strings

查看:194
本文介绍了iOS #define或全局字符串的静态const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个constants.h文件,它声明了我在整个应用程序中使用的一堆字符串。我只有字符串,没有别的。我应该使用#define还是静态NSString const? #define有效,但我听说它不是最佳做法。

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.

推荐答案

#define 是一个预处理器宏。这意味着它基本上会遍历您的代码并用您定义的内容替换您的宏。

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.

如果您使用const,它将成为指向字符串的指针在记忆中。它比在任何地方/任何地方分配相同的字符串更有效。

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.

为此,你需要.h和.m文件。您的.h文件类似于:

To do that, you'll need both .h and .m files. Your .h file will look something like:

extern NSString * const YOUR_STRING;

和你的.m档案:

NSString * const YOUR_STRING = @"your string";

这篇关于iOS #define或全局字符串的静态const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆