Coding

iOS: Creating a File to Hold Constants

It’s a good habit to keep your number and string constants in a file, instead of hardcoding them into your code. This minimises many inconveniences when you need to make changes to your code, since you only have to access that file to change those values. So how do you do that in Xcode 6 for an iOS application?

First, go to File > New > File..., and you’ll see this:
Constants

Since you’re developing an iOS application, choose Source under iOS from the left panel. Next, pick Header File from the right pane and click the Next button.

Save the header file with your desired file name (I usually pick Constants.h) into your project folder.

//
//  Constants.h
//  Luvelle Codes
//
//  Created by Michelle Teo on 12/1/15.
//  Copyright (c) 2015 Michelle Teo. All rights reserved.
//

#ifndef Luvelle_Codes_Constants_h
#define Luvelle_Codes_Constants_h

// Place your constants here!!!
extern const float kGridWidth;
extern NSString * const kErrorConnectMsg;
extern NSString * const kMenuItems[];

#endif

Now, go to File > New > File..., and select Objective-C File from iOS > Source. Give it the same name as your header file (e.g. Constants), and select “Empty File” under the File Type option. Click “Next” and save your file as Constants.m in the same project folder.


Insert the values for these constants:

//
//  Constants.m
//  Luvelle Codes
//
//  Created by Michelle Teo on 12/1/15.
//  Copyright (c) 2015 Michelle Teo. All rights reserved.
//

#import <Foundation/Foundation.h>

const float kGridWidth = 100;
NSString * const kErrorConnectMsg = @"Connection Error!";
NSString * const kMenuItems[] = {
    @"ABC", @"123", @"Do Re Me"
};

Note: If you have to access Constants.h in almost all your classes, it makes little sense to repeatedly add the import "Constants.h" statement in all of them. Follow the instructions under this post to import them conveniently using a PCH file.


2nd Note: According to Apple Guidelines, we should avoid using #define to create constants.


2 thoughts on “iOS: Creating a File to Hold Constants

Leave a Reply

Your email address will not be published. Required fields are marked *