13

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.

user1802143
  • 14,662
  • 17
  • 46
  • 55

1 Answers1

33

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.

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.

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

extern NSString * const YOUR_STRING;

And your .m file:

NSString * const YOUR_STRING = @"your string";
Bruno Koga
  • 3,864
  • 2
  • 34
  • 45
  • 1
    In simple use cases, the compiler will optimize multiple creations of the same string and create a const anyway. However, with other, non-trivial classes, it is better to have one constant value which is initialized once when the class loads (for example). Consts are also good when wanting to expose a public symbol in public API. – Léo Natan Aug 17 '13 at 00:52
  • 3
    they will both end up being stored as a constant string in the executable, and in memory... – Grady Player Aug 17 '13 at 00:53
  • What if its a format like @"this is my string with int %i"? – user1802143 Aug 17 '13 at 01:20
  • @user1802143, the `%i` part makes the string a variable, not a constant. – leanne Oct 02 '13 at 22:16
  • 2
    @leanne. No. the %i does not make it a variable. The %i is just part of the string constant. You can use it to create another string variable if you actually use it as a format string, but a format string is just a string. – chadbag May 21 '14 at 01:11
  • You're right, @chadbag. The formatted string in the `#define` is still a constant, per se. When used, the `%i` will represent a replaceable integer parameter. – leanne May 21 '14 at 19:34