It is important when you work on your application, that you use a file to store all your application-wide constants, usually strings that you would normally store things such as:
- Server URL’s, for when you access a web service
- Key tokens, such as for various third-party APIs, like TestFlight, where you have a constant key that you need to refer to.
These constants don’t usually change, but if they do change, you have a single source to change, that would be reflected Application-wide.
To better illustrate this, I will give you the example I use with one of my apps:
I start off by creating a Constants.h and Constants.m file, that I put in one of the sub-folders in my XCode application. (I have included both header and implementation file in one, for brevity).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
// Created by Doron Katz on 15/06/11.
// Copyright 2011 doronkatz.com. All rights reserved.
extern NSString* const kDBRestKitBaseURL;
extern NSString* const kDBCategoryResource;
extern NSString* const kDBSubCategoryResource;
extern NSString* const kDBBrandResource;
extern NSString* const kDBProductsResource;
extern NSString* const kTestFlightID;
extern NSString* const kMailChimpAPIKey;
extern NSString* const kMailChimpListId;
NSString* const kDBRestKitBaseURL = @"http://localhost:8888/myApp";
NSString* const kDBRestKitBaseURL = @"http://www.myserver.org.au";
NSString* const kDBCategoryResource = @"/WebServices/myApp_categories.php";
NSString* const kDBSubCategoryResource = @"/WebServices/myApp_subcategories.php";
NSString* const kDBBrandResource = @"/WebServices/myApp_brands.php";
NSString* const kDBProductsResource = @"/WebServices/myApp_products.php";
NSString* const kTestFlightID = @"12345";
NSString* const kMailChimpListId = @"222";
NSString* const kMailChimpAPIKey = @"333-us2";
As you can see, I am using various constants to refer to my web service servers, and since I use one for testing, one for production, I combine this with the use of Preprocessor directives, another important tool that you should get used to. By using preprocessors, I can #define TESTING and PRODUCTION to switch between both servers.
Going back to my example, once you have the constants files, you can import the header-file in each class you are working to, and refer to the constant. But a more logical thing for you to do, is to edit the myApp.pch file, and refer to headers that you would be using throughout your app. Just be sure to be concise, as the more stuff you add here, the more weight it adds to your performance.
1 2 3 4 5 6 7 8
I also added the pre-processor #define here, so that the app knows I am testing, which is neat.