如何在Objective-C头文件中初始化常量?

SK9*_*SK9 8 header constants objective-c

如何初始化头文件中的常量?

例如:

@interface MyClass : NSObject {

  const int foo;

}

@implementation MyClass

-(id)init:{?????;}
Run Code Online (Sandbox Code Playgroud)

unb*_*eli 17

对于"公共"常量,您将其声明为extern头文件(.h)并在实现文件(.m)中初始化它.

// File.h
extern int const foo;
Run Code Online (Sandbox Code Playgroud)

然后

// File.m
int const foo = 42;
Run Code Online (Sandbox Code Playgroud)

考虑使用enum它不只是一个,而是多个常数属于一起


Jer*_*myP 12

Objective C类不支持常量作为成员.您无法按照自己的方式创建常量.

声明与类关联的常量的最接近方法是定义返回它的类方法.您还可以使用extern直接访问常量.两者都在下面演示:

// 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
Run Code Online (Sandbox Code Playgroud)

类方法版本的一个优点是可以扩展它以非常容易地提供常量对象.您可以使用extern对象,您必须在初始化方法中初始化它们(除非它们是字符串).所以你经常会看到以下模式:

// 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
Run Code Online (Sandbox Code Playgroud)