How are constants initialized in Objective-C header files?

How do you initialize a constant in the header file?

For example:

@interface MyClass : NSObject { const int foo; } @implementation MyClass -(id)init:{?????;} 
+7
objective-c header constants
source share
3 answers

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

 // File.h extern int const foo; 

then

 // File.m int const foo = 42; 

Consider using enum if it is not one, but several constants that belong together

+16
source share

C objective classes do not support constants as members. You cannot create a constant the way you want.

The closest way to declaring a constant associated with a class is to define a class method that returns it. You can also use extern for direct access to constants. Both are shown 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 

The advantage of the class method version is that it can be extended to provide a permanent object quite easily. You can use external objects, a nut that you must initialize in the initialization method (unless they are strings). Therefore, 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 
+12
source share

An easy way for value type constants, such as integers, is to use enum hack as scheduled by unbeli.

 // File.h enum { SKFoo = 1, SKBar = 42, }; 

One of the advantages of using extern is that it was all allowed at compile time, so no memory is needed to store the variables.

Another method is to use static const , which was supposed to replace enum hack in C / C ++.

 // File.h static const int SKFoo = 1; static const int SKBar = 42; 

A quick scan through Apple headers reveals that an enumeration method is the preferred way to do this in Objective-C, and I actually find it cleaner and use it myself.

In addition, if you create parameter groups, you must use NS_ENUM to create type constants.

 // File.h typedef NS_ENUM(NSInteger, SKContants) { SKFoo = 1, SKBar = 42, }; 

Further information on NS_ENUM and cousin NS_OPTIONS is available at NSHipster .

0
source share

All Articles