Daniel Campos
Daniel Campos

Reputation: 971

Retrieve values from NSDictionary with same keys

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"image1.jpg" forKey:@"USA"];
[dict setObject:@"image2.jpg" forKey:@"USA"];
[dict setObject:@"image3.jpg" forKey:@"USA"];
[dict setObject:@"image1.jpg" forKey:@"Brazil"];
[dict setObject:@"image2.jpg" forKey:@"Brazil"];

If I use:

NSArray *keys = [dict allKeys];

Fine, I got a {USA, Brazil} Array.

All I want is a code that I get all objects for USA. If I use:

NSArray *objectsforKey = [dict objectForKey:@"USA"];

I will get an array with only one item: image1.jpg Same issue for valueforKey. I need all values for that key. Is that possible?

Upvotes: 2

Views: 5882

Answers (3)

TheTiger
TheTiger

Reputation: 13364

Its not possible. You should add an array-

 [dict setObject:@[@"image1.jpg",@"image2.jpg", @"image3.jpg"] forKey:@"USA"];

Upvotes: 2

Flo
Flo

Reputation: 5405

That is not possible. NSDictionary only stores one object per key. In your code you are replacing the previous object, when calling setObject:forKey:.

The solution is to store arrays inside the dictionary:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

NSMutableArray *USAImages = [NSMutableArray array];
[USAImages addObject:@"image1.jpg"];
[USAImages addObject:@"image2.jpg"];
[USAImages addObject:@"image3.jpg"];
dict[@"USA"] = USAImages;

NSMutableArray *BrazilImages = [NSMutableArray array];
[BrazilImages addObject:@"image1.jpg"];
[BrazilImages addObject:@"image2.jpg"];
dict[@"Brazil"] = BrazilImages;

Now you can get your filenames like this:

NSArray *USA = dict[@"USA"]; // @[@"image1.jpg",@"image2.jpg",@"image3.jpg"]
NSArray *Brazil = dict[@"Brazil"]; // @[@"image1.jpg",@"image2.jpg"]

Upvotes: 9

Baby Groot
Baby Groot

Reputation: 4279

Actually key should be unique. If you will set like this key "USA" will have value last value as "image3.jpg" and key "Brazil" will override "image1.jpg" with "image2.jpg".

Upvotes: 0

Related Questions