Correct way of defining constants in Objective-C

Just a short bookmarked post here regarding definition of constants in Cocoa code. Found the answer in this stackoverflow.com question. For those who are too lazy to click – here’s the short intro and the post itself.

You’ve probably read all over the Apple developer documentation site that certain method parameters can receive only enumerated list of values which are defined by constants. Good examples would be masks for event types (NSKeyUpMask, NSKeyDownMask, etc.), persistent store coordinator’s store types (NSSQLiteStoreType, NSBinaryStoreType and NSInMemoryStoreType) and, of course, lots of others.

So all this thing boils down to a few lines of code. Actually, to twice as many lines of code as you want to have constants. Here how it goes:

First – let’s create Constants.h and Constants.m files where we will hold our constants. Then in Constants.h we will declare our constants as pointers to NSString objects by giving them names:

// Constants.h
extern NSString * const MyOwnConstant
extern NSString * const YetAnotherConstant

And finally we define our constants in Constants.m file by assigning them some value in :

// Constants.m
NSString *MyOwnConstant = "myOwnConstant";
NSString *YetAnotherConstant = "yetAnotherConstant";

Now all you have to do is include the Constants.h file into header prefix file of your project and voilà!

If you’re smart – there’s probably two questions in your head at the moment. If you’re smarter – you’ll leave a comment. The first question is probably this: why use this approach when we can have good-ol’ #define‘s? This is very valid question.

The answer is simple (although it wasn’t so apparent to me until i read the answer) – when using this approach you can do pointer comparison (@"myString" == MyConstant) instead of string comparison ([@"myString" isEqualToString:MyConstant]). The former is wayyy faster.

The second question should be why do we use constant at all? Valid question again. You could type constant’s value in each and every place it’s being used. But here are two “buts”. First one – there’s always a human factor. You could easily mistype the string and the compiler would not complain about your grammar. But by using constants it would complain about mistyped constant name. Also (the second but) this method is more convenient since XCode tries to do his best to autocomplete stuff for us and these constants are no exception.

Happy coding!