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

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

问题描述:

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

例如:

@interface MyClass : NSObject { 

    const int foo; 

} 

@implementation MyClass 

-(id)init:{?????;} 

对于 “公众” 的常量,你在你的头文件(.h)中声明为extern并在实现文件(.M)进行初始化。

// File.h 
extern int const foo; 

然后

// File.m 
int const foo = 42; 

考虑使用enum如果它不只是一个,而是多个常量属于

+0

如果我需要'typedef NS_ENUM'会怎么样? – ManuQiao 2015-02-13 03:55:09

目标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 

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

// 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 
+0

增加了一点,我只想到 – JeremyP 2010-05-31 17:27:36

+0

很好。指定您编写的模式称为singleton并且经常用于共享应用程序中的所有内容可能会很有趣。 AppDelegate类是iPhone开发中的一个很好的例子。 – moxy 2012-05-11 18:20:40

值类型常量像整数一个简单的方法是使用enum hack作为暗示的unbeli。

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

一个优点这种过度使用extern的是,这一切都在编译时解析所以不需要内存来存放变量。

另一种方法是使用static const,这是在C/C++中取代enum hack的方法。

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

通过苹果的头快速扫描显示,枚举破解方法似乎是在Objective-C这样做的,其实我觉得它更清洁,并用它自己的首选方式。

此外,如果您正在创建多组选项,则应考虑使用NS_ENUM来创建类型安全常量。

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

更多信息关于NS_ENUM和它的堂兄NS_OPTIONS可在NSHipster