これは古い質問ですが、より現代的な構文を使用するように更新することができます。私たちは、内部NSInteger
のように表す列挙型を持っているので、私たちは辞書のキーとして格納するNSNumber
秒にそれらをボックスすることができ、その後
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
};
:まず、iOSの6のように、Appleは列挙型は以下のように定義することをお勧めします。
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
// set the value
dictionary[@(MyEnumValue1)] = @"test";
// retrieve the value
NSString *value = dictionary[@(MyEnumValue1)];
EDIT:どのようにこのメソッドを介して、この目的のために
をシングルトン辞書を作成するには、これを支援するためにシングルトン辞書を作成することができます。あなたが持っているものは何でもファイルの先頭には、使用することができます:
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;
});
:
static NSDictionary *enumTranslations;
を次に、あなたのinit
またはviewDidLoad
に(あなたはUIコントローラでこれをやっている場合)、あなたはこれを行うことができます
この辞書を外部から見えるようにするには、静的宣言をヘッダー(.h
)ファイルに移動します。
なぜアレイを使用しないのですか? – user102008