Do you use constants when working with NSDictionary?

I understand the use of constants for your names in NSDictionary to prevent typos (myName will be automatically completed vs @ "myName" will not).

I work with medium-sized dictionaries right now, and a couple of times, I mistakenly used key names and had to spend some time tracking where I missed a word.

I am wondering if you consider it appropriate to set up a constant naming scheme?

+8
ios objective-c
source share
3 answers

Yes, but I would advise defining the correct string constants, not #defines for your strings, because string constants are type safe and each 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 it in your .m file:

 static NSString *const MyConstant = @"MyConstant"; 

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

 extern NSString *const MyConstant; 

And this is in your .m file:

 NSString *const MyConstant = @"MyConstant"; 
+21
source share

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

.h file

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

By including the .h file, you can now access these values

 [dictionary objectForKey:PERSON_NAME]; 
+4
source share

Yes, it's worth it. Consistency in something like this does what you say: it reduces mistakes and saves you time.

+3
source share

All Articles