这是一个老问题,但可以更新以使用更现代的语法。首先,从 iOS 6 开始,Apple 建议将枚举定义为:
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
};
然后,由于我们在内部将枚举表示为NSIntegers,因此我们可以将它们装箱到NSNumbers 中以存储为字典的键。
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) 文件中。