8

I understand using constants for your names in a NSDictionary to prevent typos (myName will auto complete vs @"myName" won't).

i'm working with a medium size dictionaries right now and a couple of times, i've misstyped key names and had to spend some time tracking down where i miss spelled a word.

i'm wondering, do you consider it worth while to set up a constants naming scheme?

Padin215
  • 7,444
  • 13
  • 65
  • 103

3 Answers3

21

Yes, but I'd advise defining proper string constants rather than #defines for your strings because string constants are type-safe and every reference will use the same actual string object, which improves the performance of using isEqualToString: to compare them.

To define a private string constant you can put this in your .m file:

static NSString *const MyConstant = @"MyConstant";

To make it public, you can either put this in your .h file instead, or you can split the definition by putting this in your .h:

extern NSString *const MyConstant;

And this in your .m file:

NSString *const MyConstant = @"MyConstant";
Nick Lockwood
  • 40,865
  • 11
  • 112
  • 103
  • 3
    +1 very good answer and totally the way to go -- hopefully this will be read by some of my coworkers who are constantly using defines for those things; thunder and lightning shall hit them on the toilet! – Till Feb 10 '12 at 21:18
4

I usually create a GlobalDefinitions.h file and place macros that I can use in code instead of magic strings.

.h file

#define PERSON_NAME @"Person_name"
#define PERSON_BDAY @"Person_bday"

By including the .h file you can now access you values like so

[dictionary objectForKey:PERSON_NAME];
Joel Kravets
  • 2,473
  • 19
  • 16
3

Yes, it's worth it. Consistency in something like this does what you say: it cuts down on errors and saves you time.

Rayfleck
  • 12,116
  • 8
  • 48
  • 74