views:

263

answers:

2

How do you initialise a constant in a header file?

For example:

@interface MyClass : NSObject {

  const int foo;

}

@implementation MyClass

-(id)init:{?????;}
+4  A: 

For "public" constants, you declare it as extern in your header file (.h) and initialize it in your implementation file (.m).

// File.h
extern int const foo;

then

// File.m
int const foo = 42;

Consider using enum if it's not just one, but multiple constants belonging together

unbeli
Thanks for the great answer! I feared this much, I was hoping someone could prove this wrong. I have an aversion to extern :)
SpecialK
+2  A: 

Objective C classes do not support constants as members. You can't create a constant the way you want.

The closest way to declare a constant associated with a class is to define a class method that returns it. You can also use extern to access constants directly. Both are demonstrated below:

// header
extern const int MY_CONSTANT;

@interface Foo
{
}

+(int) fooConstant;

@end

// implementation

const int MY_CONSTANT = 23;

static const int FOO_CONST = 34;

@implementation Foo

+(int) fooConstant
{
    return FOO_CONST; // You could also return 34 directly with no static constant
}

@end

An advantage of the class method version is that it can be extended to provide constant objects quite easily. You can use extern objects, nut you have to initialise them in an initialize method (unless they are strings). So you will often see the following pattern:

// header
@interface Foo
{
}

+(Foo*) fooConstant;

@end

// implementation

@implementation Foo

+(Foo*) fooConstant
{
    static Foo* theConstant = nil;
    if (theConstant == nil)
    {
        theConstant = [[Foo alloc] initWithStuff];
    }
    return theConstant;
}

@end
JeremyP
Thanks for the great answer! I feared this much, I was hoping someone could prove this wrong. I have an aversion to extern :)
SpecialK
Added another bit that I just thought of
JeremyP