Where to store global constants in an iOS application?

Solution 1:

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 DEBUG
NSString* const MONAppsBaseUrl = @"http://192.168.0.123/";
#else
NSString* 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.

Solution 2:

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

Solution 3:

The way I define global constants:


AppConstants.h

extern NSString* const kAppBaseURL;

AppConstants.m

#import "AppConstants.h"

#ifdef DEBUG
NSString* const kAppBaseURL = @"http://192.168.0.123/";
#else
NSString* 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.

Solution 4:

You can also concatenate string constants like this:

  #define kBaseURL @"http://myServer.com"
  #define kFullURL kBaseURL @"/api/request"