有两种可能的方法可以使这更容易。
解决方案 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];