您误解了字典的工作原理。字典为单个键存储单个值。因此,在您的代码运行后,将保存一个键值对:=> 。如果您需要一个键来指向多个对象,那么您的键将需要指向一个(或者如果您不关心顺序),然后您从而不是从字典中添加和删除事物。myDict
@"products"
@"grapes"
NSMutableArray
NSMutableSet
NSMutableArray
如果这将成为您字典中所有内容的基本结构,您可能需要考虑为您的字典制作一个包装器,如下所示:
//DDMutableMultiValueDictionary.h
@interface DDMutableMultiValueDictionary : NSObject {
NSMutableDictionary * dict;
}
- (void) addObject:(id)value forKey:(id)key;
- (void) removeObject:(id)value forKey:(id)key;
- (BOOL) containsObject:(id)value forKey:(id)key;
@end
//DDMutableMultiValueDictionary.m
#import "DDMutableMultiValueDictionary.h"
@implementation DDMutableMultiValueDictionary
- (id) init {
if (self = [super init]) {
dict = [[NSMutableDictionary alloc] init];
}
return self;
}
- (void) dealloc {
[dict release];
[super dealloc];
}
- (void) addObject:(id)value forKey:(id)key {
NSMutableArray * values = [dict objectForKey:key];
if (values == nil) {
values = [NSMutableArray array];
[dict setObject:values forKey:key]
}
[values addObject:value];
}
- (void) removeObject:(id)value forKey:(id)key {
NSMutableArray * values = [dict objectForKey:key];
[values removeObject:value];
}
- (BOOL) containsObject:(id)value forKey:(id)key {
NSMutableArray * values = [dict objectForKey:key];
return [values containsObject:value];
}
@end
这无论如何都不完整,但它让您了解如何制作它。