Questa è una vecchia domanda, ma può essere aggiornata per utilizzare una sintassi più moderna. In primo luogo, come di iOS 6, Apple consiglia di enumerazioni essere definiti come:
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
};
Poi, dal momento che abbiamo l'enum rappresentato come NSInteger
s internamente, possiamo box in NSNumber
s per memorizzare come la chiave per un dizionario .
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
// set the value
dictionary[@(MyEnumValue1)] = @"test";
// retrieve the value
NSString *value = dictionary[@(MyEnumValue1)];
EDIT: Come creare un dizionario Singleton per questo scopo
Attraverso questo metodo, è possibile creare un dizionario Singleton per assistere con questo. Nella parte superiore di qualsiasi file che si dispone, è possibile utilizzare:
static NSDictionary *enumTranslations;
Poi, nel tuo init
o viewDidLoad
(se si sta facendo questo in un controller di interfaccia utente), si può fare questo:
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;
});
Se si desidera che questo dizionario sia visibile esternamente, spostare la dichiarazione statica sul file di intestazione (.h
).
perché non usi solo un array? – user102008