The class of object c-constants

I have some constants encoded in several different classes viewController and NSObject atm. One of the guys in my work said that I should put them in my class (i.e. the Constant Class)

I am wondering what the pro and con of this type of design are, and also if there is something that needs to be done, any clarifications on how to do this would be great.

for example, am I just creating a new NSObject class and have the #defines set? then when I need to use them, I just subclass my class of constants and use constants inside this class, like any other method or variable from another class?

i.e.

myclass.theConstant 

any help would be very helpful.

+6
source share
2 answers

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

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

Constants are usually not methods or do not define. These are just constant global variables as shown above. You should avoid #define wherever possible, but there are some places that are very useful (for example, persistent UIColor objects that otherwise disappoint initialization).

Spend some time in Apple's header files to see examples. Take a look at UIWindow.h, UITableViewCell.h, and UITableView.h for some good examples of how constants are usually defined.

+11
source

If you just have #defines they don’t have to be in any class - just paste them into your .h file.

0
source

Source: https://habr.com/ru/post/913874/


All Articles