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.
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:
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
UIColorobjects, 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.