How are constants initialized in Objective-C header files?
How do you initialise a constant in a header file?
For example:
@interface My开发者_如何学GoClass : NSObject {
const int foo;
}
@implementation MyClass
-(id)init:{?????;}
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
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
A simple way for value type constants like integers is to use the enum hack as hinted by unbeli.
// File.h
enum {
SKFoo = 1,
SKBar = 42,
};
One advantage to this over using extern
is that it's all resolved at compile time so there no memory is needed to hold the variables.
Another method is to use static const
which is what was to replace the enum hack in C/C++.
// File.h
static const int SKFoo = 1;
static const int SKBar = 42;
A quick scan through Apple's headers shows that the enum hack method appears to be the preferred way of doing this in Objective-C and I actually find it cleaner and use it myself.
Also, if you are creating groups of options you should consider using NS_ENUM
to create a typesafe constants.
// File.h
typedef NS_ENUM(NSInteger, SKContants) {
SKFoo = 1,
SKBar = 42,
};
More info on NS_ENUM
and it's cousin NS_OPTIONS
is available at NSHipster.
精彩评论