Wednesday, Nov 25

Defining Constants in Objective-C


As it is a good idea to separate your data from your logic, I needed to add a couple of constants to a practice timer app and I found a couple of good resources that I decided to combine together to make it easier to reference in the future.

Global Constants

There’s a few different ways to create constants in Objective-C, but the easiest way is to use #define statements.

To define global constants, create a new header file and give it a name - like so:

//
//  Constants.h
//  NSTimers
//
//  Created by Shani on 11/25/15.
//  Copyright © 2015 Shani Rivers. All rights reserved.
//

// Constants for calculating the minutes and the hours for the timer
#define SEC_PER_MIN        60
#define SEC_PER_HOUR    3600

And to use these constants in your project, you need to import your header file in each implementation file (*.m) where you’ll be referencing the constants.

#import "Constants.h"

- (void)countTimer {
    // int to count and calculations for timer display
    countInt += 1;
    int secLeft = countInt % SEC_PER_MIN;
    int minutes = countInt / SEC_PER_MIN;
    int minLeft = minutes % SEC_PER_MIN;
    int hour = minutes / SEC_PER_HOUR;

    self.Label.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hour,minLeft, secLeft];
}
@end

Constants.h/m Pairs

If you need to go beyond simple preprocessor directives and implement a full blown Constants.h/m pair (for comparisons and what not), then do the following:

Define these constants in a .m file like so:

// Constants.m
NSString *const MyFirstConstant = @"FirstConstant";
NSString *const MySecondConstant = @"SecondConstant";

Constants.m should be added to your application/framework's target so that it is linked in to the final product.

The advantage of using string constants instead of #define'd constants is that you can test for equality using pointer comparison (stringInstance == MyFirstConstant), which is much faster than string comparison ([stringInstance isEqualToString:MyFirstConstant]).

References

Define Constants in Objective C
Stackoverflow


Share Defining Constants in Objective-C: