Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to store global constants in an iOS application?

Most of the models in my iOS app query a web server. I would like to have a configuration file storing the base URL of the server. It will look something like this:

// production // static NSString* const baseUrl = "http://website.com/"  // testing static NSString* const baseUrl = "http://192.168.0.123/" 

By commenting out one line or the other, I can instantly change which server my models point to. My question is, what's the best practice for storing global constants in iOS? In Android programming, we have this built-in strings resource file. In any Activity (the equivalent of a UIViewController), we can retrieve those string constants with:

String string = this.getString(R.string.someConstant); 

I was wondering if the iOS SDK has an analogous place to store constants. If not, what is the best practice in Objective-C to do so?

like image 624
JoJo Avatar asked Aug 19 '11 01:08

JoJo


People also ask

What is global constant in programming?

Global Constants. A global constant is a literal value to which you assign a name. Like a global variable, you can access the value of the global constant from any script or 4GL procedure in the application. You set the value for the global constant when you declare it.


1 Answers

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.

like image 193
justin Avatar answered Oct 06 '22 10:10

justin