0

I need to define some (static) strings that i'm going to use multiple times inside my app, I searched a little and I found that I can declare a class like this:

// Constants.h 
FOUNDATION_EXPORT NSString *const MyFirstConstant;
FOUNDATION_EXPORT NSString *const MySecondConstant;
//etc.


// Constants.m 
NSString *const MyFirstConstant = @"FirstConstant";
NSString *const MySecondConstant = @"SecondConstant"; 

And then by importing the Constants.h in my files I can use those strings, but is it the right approach to my needs?

I'm using Objective-C

LS_
  • 6,763
  • 9
  • 52
  • 88
  • 1
    Yeah, except drop the use of `FOUNDATION_EXPORT` and use `extern` instead. – trojanfoe Nov 03 '15 at 14:18
  • 1
    That works. Another approach is to use the same syntax, but do it in .h/.m files that logically "own" the constants rather than in a general-purpose location – Phillip Mills Nov 03 '15 at 14:23
  • This has been answered several times, this is my favourite one [here](http://stackoverflow.com/a/17228508/1792433) – gomezluisj Nov 03 '15 at 15:07

2 Answers2

3

Yes, that is correct. FOUNDATION_EXPORT ultimately resolves to the string extern. That tells the compiler that the symbol is defined somewhere else, and leave it to the linker to deal with. The declaration in the *.m is where the storage is actually defined, and that's only compiled and linked in once. The linker finds that reference and fixes up all the extern references that get imported into other files to point to that one.

Avi
  • 7,469
  • 2
  • 21
  • 22
  • You're welcome. I have found that the best SO answers include a solid explanation. I hope to carry on that tradition so that people can learn, and not just copy+paste. – Avi Nov 03 '15 at 14:46
2

Yes it is.

I do it like this:

// Constants.h 
extern NSString *const kMyFirstConstant;

// Constants.m
NSString *const kMyFirstConstant = @"FirstConstant";
Abhinav
  • 37,684
  • 43
  • 191
  • 309