Where to store global constants in an iOS application? Where to store global constants in an iOS application? ios ios

Where to store global constants in an iOS application?


Well, you want the declaration local to the interfaces it relates to -- the app-wide constants file is not a good thing.

As well, it's preferable to simply declare an extern NSString* const symbol, rather than use a #define:


SomeFile.h

extern NSString* const MONAppsBaseUrl;

SomeFile.m

#import "SomeFile.h"#ifdef DEBUGNSString* const MONAppsBaseUrl = @"http://192.168.0.123/";#elseNSString* const MONAppsBaseUrl = @"http://website.com/";#endif

Apart from the omission of the C++ compatible Extern declaration, this is what you will generally see used in Apple's Obj-C frameworks.

If the constant needs to be visible to just one file or function, then static NSString* const baseUrl in your *.m is good.


You could also do a

#define kBaseURL @"http://192.168.0.123/"

in a "constants" header file, say constants.h. Then do

#include "constants.h"

at the top of every file where you need this constant.

This way, you can switch between servers depending on compiler flags, as in:

#ifdef DEBUG    #define kBaseURL @"http://192.168.0.123/"#else    #define kBaseURL @"http://myproductionserver.com/"#endif


The way I define global constants:


AppConstants.h

extern NSString* const kAppBaseURL;

AppConstants.m

#import "AppConstants.h"#ifdef DEBUGNSString* const kAppBaseURL = @"http://192.168.0.123/";#elseNSString* const kAppBaseURL = @"http://website.com/";#endif

Then in your {$APP}-Prefix.pch file:

#ifdef __OBJC__  #import <UIKit/UIKit.h>  #import <Foundation/Foundation.h>  #import "AppConstants.h"#endif

If you experience any problems, first make sure that you have the Precompile Prefix Header option set to NO.