好像你可以使用NSSet中作为关键的NSDictionary:
NSMutableDictionary * dict = [NSMutableDictionary dictionary];
NSSet * set;
set = [NSSet setWithObjects:@"a", @"b", @"c", @"d", nil];
[dict setObject:@"1" forKey:set];
set = [NSSet setWithObjects:@"b", @"c", @"d", @"e", nil];
[dict setObject:@"2" forKey:set];
id key;
NSEnumerator * enumerator = [dict keyEnumerator];
while ((key = [enumerator nextObject]))
NSLog(@"%@ : %@", key, [dict objectForKey:key]);
set = [NSSet setWithObjects:@"c", @"b", @"e", @"d", nil];
NSString * value = [dict objectForKey:set];
NSLog(@"set: %@ : key: %@", set, value);
输出:
2009-12-08 15:42:17.885 x[4989] (d, e, b, c) : 2
2009-12-08 15:42:17.887 x[4989] (d, a, b, c) : 1
2009-12-08 15:42:17.887 x[4989] set: (d, e, b, c) : key: 2
另一种方法是使用NSMutableDictionary
持有多个NSSet
“项目和价格第作为一个关键,但是注意到,如果价格不是唯一的,这将不起作用。
您可以手动检查集合是否在字典中,通过遍历项目和每个集合使用isEqualToSet:
- 除非任何人都能想出更好的方法。
如果您返回的价格(关键),如果它不是你可以用一个价格,主要部件插入:
@interface ShoppingList : NSObject
{
NSMutableDictionary * shoppingList;
}
- (void)setList:(NSSet*)aList
forPrice:(double)aPrice
{
[shoppingList setObject:aList forKey:[NSNumber numberWithDouble:aPrice]];
}
- (double)priceForList:(NSSet*)aList
{
id key;
NSEnumerator * enumerator = [shoppingList keyEnumerator];
while ((key = [enumerator nextObject]))
{
NSSet * list = [shoppingList objectForKey:key];
if ([aList isEqualToSet:list])
{
return [(NSNumber*)key doubleValue];
}
}
return 0.0;
}
{
ShoppingList * shoppingList = [[ShoppingList alloc] init];
NSSet * list;
double price = 0.0;
list =
[NSSet setWithObjects:@"apple",@"green_apple",@"pineapple",nil];
[shoppingList setList:list forPrice:9.99];
list =
[NSSet setWithObjects:@"grapes",@"banana",@"strawberries",@"apple",nil];
[shoppingList setList:list forPrice:15.99];
list =
[NSSet setWithObjects:@"orange",@"grapes",@"green_apple",nil];
[shoppingList setList:list forPrice:7.50];
// searching for this
list =
[NSSet setWithObjects:@"grapes",@"banana",@"strawberries",@"apple",nil];
price = [shoppingList priceForList:list];
if (price != 0.0)
{
NSLog(@"price: %.2f, for pricelist: %@", price, list);
}
else
{
NSLog(@"shopping list not found: %@", list);
[shoppingList setList:list forPrice:15.99];
}
}
但是如果价格不是唯一的呢? – erotsppa 2009-12-07 13:59:46
然后将对象存储在NSMutableSets中,而不是使用相同的价格检查添加新的集合,以查看是否存在具有该价格的集合,并在其中添加对象。 – 2009-12-07 17:04:25
所有我能想到的情况下,价格不唯一的情况是创建记录,无论是NSSet的自定义类或NSDictionary,项目列表和价格,并且对于密钥,您可以使用类似唯一id(int)的内容。 – stefanB 2009-12-07 19:57:32