20 Feb 2011

Defining project constants

Objective C No Comments

Just a quick tip for creating a globally accessible bunch of constants for your iOS project. In AS3 I would use a class with a public static variable but in Objective C you can use constants or definitions and there are probably several other ways to do it.

To use constants globally:

  1. Define a new Objective C class which extends NSObject for example called ProjectConstants
  2. Above the implementation line in its header (ProjectConstants.h) file add this:
    extern NSString * const PAGE_TITLE;
  3. In the implementation (ProjectConstants.m) file add:
    NSString * const PAGE_TITLE = @"My Page Title";
  4. Access it globally by importing the ProjectConstants.h and then you can use PAGE_TITLE anywhere in the project:
    NSString *pgTitle = PAGE_TITLE;
    myLabel.text = pgTitle;

Another quicker way is to use definitions in your implementation of your .m file such as: #define PAGE_TITLE @"Title"
The disadvantage of that is you can’t compare strings using pointer comparison i.e. (myString == MyConstant) but you can still use [myString isEqualToString:MyConstant] but its not as easy to read, and apparently not that fast either.

No Responses to “Defining project constants”

Leave a Reply