有兩種可能的方法可以使這更容易。
解決方案1 如果您使用的是ACSoundId爲重點,以你的NSDictionary,你可以只使用一個NSArray:
typedef enum {
kSoundColorSelection1 = 0,
kSoundColorSelection2 = 1,
kSoundColorSelection3 = 2,
kSoundFill1 = 3,
kSoundFill2 = 4,
kSoundSizeSelectionBig = 5,
kSoundSizeSelectionMedium = 6
} ACSoundId;
存儲在同一順序的數組它們在定義的聲音以上枚舉:
templatesSounds = [[NSArray alloc] initWithObjects:@"color_selection1.caf",
@"color_selection2.caf",
@"color_selection3.caf",
@"color_fill1.caf",
@"color_fill2.caf",
@"size_selection_big.caf",
@"size_selection_medium.caf",
nil];
由於聲音的索引將關聯到枚舉的值,它的工作類似於NSDirectory:
queuedSound = [templatesSounds objectAtIndex:kSoundColorSelection2];
解決方案2 或者你可以創建一個類,以使其更容易在一個NSDictionary使用整數作爲鍵:
定義類別:
@interface NSMutableDictionary (NSNumberDictionary)
- (void) setObject:(id)anObject forNumber:(NSInteger)aNumber;
- (void) removeObjectForNumber:(NSInteger)aNumber;
- (id) objectForNumber:(NSInteger)aNumber;
@end
落實類別:
@implementation NSMutableDictionary (NSNumberDictionary)
- (void) setObject:(id)anObject forNumber:(NSInteger)aNumber
{
NSNumber * number;
number = [[NSNumber alloc] initWithInteger:aNumber];
[self setObject:anObject forKey:number];
[number release];
return;
}
- (void) removeObjectForNumber:(NSInteger)aNumber
{
NSNumber * number;
number = [[NSNumber alloc] initWithInteger:aNumber];
[self removeObjectForKey:number];
[number release];
return;
}
- (id) objectForNumber:(NSInteger)aNumber
{
NSNumber * number;
id object;
number = [[NSNumber alloc] initWithInteger:aNumber];
object = [self objectForKey:number];
[number release];
return(object);
}
@end
使用類別:
templatesSounds = [[NSMutableDictionary alloc] initWithWithCapacity1];
[templatesSounds setObject:@"color_selection1.caf" forNumber:kSoundColorSelection1];
[templatesSounds setObject:@"color_selection2.caf" forNumber:kSoundColorSelection2];
[templatesSounds setObject:@"color_selection3.caf" forNumber:kSoundColorSelection3];
[templatesSounds setObject:@"color_fill1.caf" forNumber:kSoundColorFill1];
[templatesSounds setObject:@"color_fill2.caf" forNumber:kSoundColorFill2];
可以使用NSNumber作爲字典中的鍵。 –
既然你想使用整數值作爲鍵,我會建議明確設置枚舉中的所有值。 – Joe
爲什麼不把它們從筆尖加載? –