I'm developing a Cocoa app, and I'm using constant NSStrings as ways to store key names for my preferences. I understand this is a good idea because it allows easy changing of keys if necessary. Plus, it's the whole 'separate your data from your logic' notion. Anyway, is there a good way to make these constants defined once for the whole app? I'm sure that there's an easy and intelligent way, but right now my classes just redefine the ones they use. Suck.
You should create a header file like
// Constants.h extern NSString * const MyFirstConstant; extern NSString * const MySecondConstant; //etc.
You can include this file in each file that uses the constants or in the pre-compiled header for the project.
You define these constants in a .m file like
// Constants.m NSString * const MyFirstConstant = @"FirstConstant"; NSString * const MySecondConstant = @"SecondConstant";
Constants.m should be added to your application/framework's target so that it is linked in to the final product.
The advantage of using string constants instead of
#define'd constants is that you can test for equality using pointer comparison (
stringInstance == MyFirstConstant) which is much faster than string comparison (
[stringInstance isEqualToString:MyFirstConstant]) (and easier to read, IMO).