The Best Way to Declare a Constant in Objective-C

Thanks to Barry Wark From [Here]

Create a header file like

// Constants.h
extern NSString * const MyFirstConstant;
extern NSString * const MySecondConstant;
//etc. 

You can include this file in each file that uses the constants or in the pre-compiled header for the project.

You define these constants in a .m file like

// 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 constants is that you can test for equality using pointer comparison (stringInstance == MyFirstConstant) which is much faster than string comparison ([stringInstance isEqualToString:MyFirstConstant]) (and easier to read, IMO).

One response to “The Best Way to Declare a Constant in Objective-C

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>