Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are constants initialized in Objective-C header files?

How do you initialise a constant in a header file?

For example:

@interface MyClass : NSObject {

  const int foo;

}

@implementation MyClass

-(id)init:{?????;}
like image 388
SK9 Avatar asked May 31 '10 09:05

SK9


2 Answers

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

like image 97
unbeli Avatar answered Sep 20 '22 15:09

unbeli


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
like image 23
JeremyP Avatar answered Sep 17 '22 15:09

JeremyP