views:

433

answers:

1
+1  Q: 

Integer constants

If I declare a string constant like so:

You should 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";

What do I do to define integer constants?

Thanks,

Dan

+4  A: 

Replace NSString* with NSInteger.

This is true of any constant type, be it a primitive such as int/float, or a class such as NSString or NSInteger.

The only thing to be aware of is whether you desire a constant or a pointer to a constant (such as withNSString), and how it's initialized in the .m file

Integer example:

// constants.h
extern NSInteger const MyIntegerConstant;

// constants.m
NSInteger const MyIntegerConstant = 666;

(Note: for the reason why NSInteger instead of just regular "int", see this post)

Class example:

// constants.h
extern MyClass* const MyClassConstant;

// constants.m
MyClass* const MyClassConstant= [[MyClass alloc] initWith: paramOne and:paramTwo];
Andrew Grant
Thanks andrew - Were would this class be deallocated?
Dan Morgan
It wouldn't be, it's memory would be cleaned up when the program exits. If you wish to have manual control over this you can add initializeConsts / releaseConsts functions to the beginning/end of your program
Andrew Grant
Thanks andy - I'm using the above code in my add and I'm getting the compile error in my Switch statements:"MyIntegerConstant" does not equate to an integer
Dan Morgan
Post the code in a separate question!
Andrew Grant