19

What is the best way to define a globally accessible string?

I see that for integer it's usually like this #define easy 0

However, how can I emulate that for NSString?
I tried static NSString *BACKGROUND = @"bg.png";
While that work, it does give a warning saying the variable is never used. (I have all these in a .h file)

Doing NSString *const BACKGROUND = @"bg.png"; is even worse since it says duplicate variable when I import the file.

I see that #define BACKGROUND @"bg.png" seems to work too.

So I guess what is the difference between when to use #define, const & static

Thanks,
Tee

jscs
  • 63,694
  • 13
  • 151
  • 195
teepusink
  • 27,444
  • 37
  • 107
  • 147
  • 1
    Another possibility is to load localized strings from resources. See http://developer.apple.com/mac/library/documentation/cocoa/conceptual/LoadingResources/Strings/Strings.html – Kristopher Johnson Aug 16 '10 at 21:21

2 Answers2

44

This is the correct way to do it. Make some new blank .h file and .m. In your .h file:

extern NSString* const BACKGROUND;

In your .m file:

NSString* const BACKGROUND = @"bg.png";
Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
Matt Williamson
  • 39,165
  • 10
  • 64
  • 72
  • 4
    It's actually `extern NSString *const`--otherwise, the contents of the string (i.e. `*BACKGROUND`) are marked const rather than the pointer. – Jonathan Grynspan Aug 16 '10 at 20:58
  • 3
    When you say correct answer, what do you mean? Is it better to use extern const than using #define? Is it due to performance – carbonr Oct 05 '12 at 20:48
  • 7
    If you do a define, it basically does a search and replace through your whole code base. If you use a const, it will be a 32/64 bit integer pointing to the string in memory. Much more efficient than having the string allocating memory wherever it is used. – Matt Williamson Oct 07 '12 at 04:40
  • 4
    @Matt Williamson #define STRING @"888" will replace all occurrences in your source at compile time with @"888" before compiling. However, I believe the compiler will take all the occurrences of @"888" and just allocate it once and point to it wherever it is used. I believe the ObjC runtime optimizes that down to one allocation at compile time with the string data embedded in your app data section. – chadbag May 21 '14 at 01:06
7

You might want to consider using a property list to store your strings. This lets your code stay flexible for future updates, especially if you add support for localization.

Tim Rupe
  • 4,323
  • 1
  • 22
  • 23