這是一個老問題,但可以更新爲使用更現代的語法。首先,iOS 6中,蘋果建議枚舉被定義爲:
typedef NS_ENUM(NSInteger, MyEnum) {
MyEnumValue1 = -1, // default is 0
MyEnumValue2, // = 0 Because the last value is -1, this auto-increments to 0
MyEnumValue3 // which means, this is 1
};
然後,因爲我們有內部表示爲NSInteger
S中的枚舉,我們可以框它們變成NSNumber
s到存儲作爲字典的關鍵。
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
// set the value
dictionary[@(MyEnumValue1)] = @"test";
// retrieve the value
NSString *value = dictionary[@(MyEnumValue1)];
編輯:如何創建一個單獨的字典用於此目的
通過這種方法,您可以創建一個單獨的字典,以協助這一點。在你擁有的任何文件上,你可以使用:
static NSDictionary *enumTranslations;
在
然後你init
或viewDidLoad
(如果你在一個UI控制器這樣做),你可以這樣做:
static dispatch_once_t onceToken;
// this, in combination with the token above,
// will ensure that the block is only invoked once
dispatch_async(&onceToken, ^{
enumTranslations = @{
@(MyEnumValue1): @"test1",
@(MyEnumValue2): @"test2"
// and so on
};
});
// alternatively, you can do this as well
static dispatch_once_t onceToken;
// this, in combination with the token above,
// will ensure that the block is only invoked once
dispatch_async(&onceToken, ^{
NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
mutableDict[@(MyEnumValue1)] = @"test1";
mutableDict[@(MyEnumValue2)] = @"test2";
// and so on
enumTranslations = mutableDict;
});
如果您希望此字典在外部可見,請將靜態聲明移至您的標題(.h
)文件。
爲什麼你不使用數組? – user102008 2011-07-29 23:38:14