6

I have some constants coded into a few different viewController and NSObject classes atm. One of the guys at my work said I should put them into a class of their own (i.e. a constants class)

I am wondering what the pro's and con's of this type of design would be and also if its something that should be done any clarification on how to do it would be great.

for instance, do I just create a new NSObject class and have a bunch of #defines in it? then when I need to use them do i just subclass my constants class and use the constants inside this class like I would any other method or variable from another class?

i.e.

myclass.theConstant

any help would be greatly appreicated.

C.Johns
  • 10,185
  • 20
  • 102
  • 156

2 Answers2

11

Put constants with the things that use them. Do not create a global "everything constant" file. This makes code reuse a huge headache. For example, if you post a notification, you need a notification name string. So you put that in the class that posts the notification:

.h
extern NSString * const MYObjectDidSomethingNotification;

.m
NSString * const MYObjectDidSomethingNotification = @"MYObjectDidSomethingNotification";

Constants are generally not methods or defines. They're just constant globals like above. You should avoid #define wherever possible, but there are some places it's quite useful (like constant UIColor objects, which are frustrating to initialize otherwise).

Spend a little time in the Apple header files to see examples. Look in UIWindow.h, UITableViewCell.h, and UITableView.h for a couple of good examples of how constants are generally defined.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • okay cool, thank you for your reply. why is #define bad? just out of curiosity. – C.Johns Apr 22 '12 at 22:57
  • I am also wondering why defines are bad for constants. Is it because of the lack of type safety? – borrrden Apr 22 '12 at 23:33
  • 4
    Scoping. Type safety. Can be evaluated in the debugger. Better information hiding. Changing a constant does not require recompiling the entire program. Avoids mind-bending compile problems when defines are accidentally redefined. There are exceptions where #define is required and in a few case preferred. But your default should be to write your code in Objective-C, not in the preprocessor macro language. Again, look at the Apple SDK and you'll notice a conspicuous lack of #define except in very specific cases (like NSAssert). – Rob Napier Apr 23 '12 at 00:19
0

If you just have #defines they don't need to be in any class -- just stick them in their own .h file.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151