»
S
I
D
E
B
A
R
«
Global Constants in Objective-C
November 28th, 2009 by admin

A good way to make constants defined once for the whole app is to 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’d 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).

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay



Similar Posts:
Leave a Reply

Powered by WP Hashcash

»  Substance: WordPress   »  Style: Ahren Ahimsa