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

8
如何在头文件中初始化常量?
例如:
@interface MyClass : NSObject {

  const int foo;

}

@implementation MyClass

-(id)init:{?????;}
3个回答

19

对于“公有”常量,您可以在头文件(.h)中声明extern,并在实现文件(.m)中初始化它。

// File.h
extern int const foo;
那么
// File.m
int const foo = 42;

如果不仅仅是一个常量,而是多个相关的常量,考虑使用enum


如果我需要使用 typedef NS_ENUM 呢? - ManuQiao

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

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

// 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
很好。可能有趣的是指出你所写的模式被称为单例,并且经常用于在应用程序中共享东西。在iPhone开发中,一个很好的例子就是AppDelegate类。 - moxy

0

对于像整数这样的值类型常量,一种简单的方法是使用枚举hack,正如unbeli所提示的那样。

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

相比使用extern,这种方法的优点在于它在编译时全部解决,因此不需要内存来保存变量。

另一种方法是使用static const,这是用于替换C/C++中枚举hack的方法。

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

快速浏览Apple的头文件,显示枚举hack方法似乎是在Objective-C中执行此操作的首选方式,我实际上发现它更清晰,并且自己使用它。
另外,如果您正在创建选项组,则应考虑使用NS_ENUM创建类型安全常量。
// File.h
typedef NS_ENUM(NSInteger, SKContants) {
    SKFoo = 1,
    SKBar = 42,
};

关于NS_ENUM及其近亲NS_OPTIONS的更多信息,请参见NSHipster


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接