Concatenate Strings with Defines

03 May 2014

I have a project that uses URL’s for my test environment when I am debugging and URLs to the production environment. These URL’s are long and the API team seems to keep changing them. Originally, I had the URL’s in each of the classes that talked to the API and they looked something like this.

	#if defined(DEBUG) || defined(STAGING)
	#define kAPIURL @"https://myclient.com/api/staging/comments/"
	#else
	#define kAPIURL @"https://myclient.com/api/a/comments/"
	#endif

The variables DEBUG and STAGING are defined in my project’s Build Settings as Preprocessor Macros.

This worked pretty well, but it didn’t scale. When I had 15 different classes for different API calls and the root url of the server changes, I had a lot of searching and replacing to do.

Now I have placed the root of the URL into the .pch file and I just concatenate that root to the API signature in each class. So, the code looks like this.

####My .pch file

	#if defined(DEBUG) || defined(STAGING)
		#define kROOTURL @"https://myclient.com/api/staging/"
	#else
		#define kROOTURL @"https://myclient.com/api/a/"
	#endif

####Each class file

#define kAPIRUL kROOTURL @"the_api_call"

The #define macro will concatenate the various items on the list and assign the value to the first item. Much easier.