Where do you declare a constant in Objective-C?

Best practice would be to declare it in your .h and .m files. See Constants in Objective-C for a very detailed set of answers regarding this same question.


There are two ways to accomplish this:

1st option- As previous replies pointed, in the .h file:

myfile.h
extern const int MY_CONSTANT_VARIABLE;

and in myfile.m define them

myfile.m    
const int MY_CONSTANT_VARIABLE = 5;

2nd option- My favourite:

myfile.h
static const int MY_CONSTANT_VARIABLE = 5 ;

Declare it in a source file and have external linkage to it( using extern keyword ) so as to use in all other source files.


You can declare in the header, define it in a code file. Simply declare it as

extern const double EARTH_RADIUS;

then in a .m file somewhere (usually the .m for the .h you declared it in)

const double EARTH_RADIUS = 6353;

Tags:

Objective C