Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

objective c constants class

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.

like image 998
C.Johns Avatar asked Apr 22 '12 22:04

C.Johns


People also ask

What is constant in ios?

Constants refer to fixed values that a program may not alter during its execution. Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal.


1 Answers

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.

like image 173
Rob Napier Avatar answered Oct 09 '22 19:10

Rob Napier