2010-05-31 70 views

回答

16

對於 「公衆」 的常量,你在你的頭文件(.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

12

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

0

值類型常量像整數一個簡單的方法是使用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