What would you consider best practice to store constants (like file names for property lists) in objective-c?
I would like to improve the hard coded “Config.plist” in the following code:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
NSDictionary *rows = [[NSDictionary alloc]initWithContentsOfFile:plistPath];
The best solution usually is to move this kind of logic into a model object like
MYConfiguration. That way you can queryMYConfigurationwith explicit methods, and never directly access theNSDictionary.Regarding the name of that file, there are many approaches to abstracting it, depending on how much reuse you really need (it is possible to go overboard here).
First is the constant. In
MYConfiguration.m, you can put a private constant like this:You can also have a method that returns the path:
It’s not uncommon to hard-code the name of the file directly in
pathToConfigurationFilerather than having a constant. Constants often are only needed in cases where the value is used more than once. If a given constant only appears one time, then moving the value elsewhere can sometimes make the code harder to understand. These are just guidelines, not rules.If you need the constant itself to be publicly available, then you declare it this way in
MYConfiguration.h:and then define it in .m:
But the key in all of this is that you define these constants in a header related to the use of the constant. You don’t create some central “MYGlobals” dumping ground for everything.