这是一个老问题,但可以更新为使用更现代的语法。首先,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