如何初始化頭文件中的常量?常量是如何在Objective-C頭文件中初始化的?
例如:
@interface MyClass : NSObject {
const int foo;
}
@implementation MyClass
-(id)init:{?????;}
如何初始化頭文件中的常量?常量是如何在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
如果它不只是一個,而是多個常量屬於
目標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
值類型常量像整數一個簡單的方法是使用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。
如果我需要'typedef NS_ENUM'會怎麼樣? – ManuQiao 2015-02-13 03:55:09