Reputation: 3131
i have data in NSDictionary like below :
Value : Football, Key: SPORT
Value : Cricket, Key: SPORT
Value : Fastrack, Key: PRODUCT/SERVICE
Value : Audi USA, Key: CARS
Value : BMW, Key: CARS
Value : Facebook, Key: PRODUCT/SERVICE
Value : TED, Key: WEBSITE
Value : National Geographic, Key: MEDIA/NEWS/PUBLISHING
Value : MyWebProduct, Key: WEBSITE
i want grouping of values according to key. what i need to do in this case or another suitable idea to implement this. I want result to be display something like :
SPORT : Football, Cricket
CARS : Audi, BMW
...
any help appreciable ...
Upvotes: 1
Views: 744
Reputation: 5858
Since you have multiple objects grouped under the same key, a dictionary of arrays would be a suitable structure to contain your data.
NSMutableDictionary *dict = [ [ NSMutableDictionary alloc ] init ];
NSArray *myItems = [ [ NSArray alloc ] initWithObjects:@"item one", @"item two", nil ];
[ dict setObject:myItems forKey:@"group of items" ];
Then you can access the group using
[dict objectForKey:@"group of items"]
Upvotes: 1
Reputation: 7707
Would this work for you, as a category on NSMutableDictionary:
- (void)setObject:(id)object inArrayForKey:(id <NSCopying>)key
{
id current = [self objectForKey:key];
if (!current || ![current isKindOfClass:[NSArray class]]) {
[self setObject:@[object] forKey:key];
} else {
[self setObject:[(NSArray *)current arrayByAddingObject:object] forKey:key];
}
}
Basically, you would then have a clean interface adding an item into an array associated with the key. You could choose to only make it an array if there was more than one item, if that's your preference.
If you're not familiar with adding categories, they allow you to add methods to existing classes. In Xcode just do new file > objective-C category and add the category on NSMutableDictionary
.
Upvotes: 1
Reputation:
NSDictionary
cannot be sorted by default. If you want sorted dictionary, go on and implement your own subclass of it (this is one of the few valid reasons for which you can subclass a standard container object).
Upvotes: 0