如何在头文件中初始化常量?
例如:
例如:
@interface MyClass : NSObject {
const int foo;
}
@implementation MyClass
-(id)init:{?????;}
@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
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
对于像整数这样的值类型常量,一种简单的方法是使用枚举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;
NS_ENUM
创建类型安全常量。// File.h
typedef NS_ENUM(NSInteger, SKContants) {
SKFoo = 1,
SKBar = 42,
};
关于NS_ENUM
及其近亲NS_OPTIONS
的更多信息,请参见NSHipster。
typedef NS_ENUM
呢? - ManuQiao