Suresh Peddisetti
Suresh Peddisetti

Reputation: 3812

Storing Multiple Values to a Single Key in NSDictionary

In my application i am getting data from the server.i parsed the data and added to individual arrays. Here i am having 2 arrays.

For example

Array A : @"1",@"2",@"3",@"2",@"3",@"4",etc.. Array B : @"A",@"B",@"C",@"D",@"E",@"F",etc..

Now i want to create a Dictionary with Array A as keys and Array B as Values. i am trying to create Dictionary like this:

dataDict = [NSDictionary dictionaryWithObjects:B forKeys:A];

But it is giving only single value for a single Key. here how can i store multiple values for a single key.

Upvotes: 0

Views: 2643

Answers (2)

Caleb
Caleb

Reputation: 125037

For Different keys its working. But my problem is Storing multiple values for single key.

You can't store multiple values for a single key directly -- dictionaries can only have one value per key. What you can do is store an array as the value. So, you could create a mutable dictionary and add the keys and values one at a time. Make the values all mutable arrays, and check for an existing value for the given key before setting it. If you find one, add the new value to the array.

Upvotes: 4

Akhilrajtr
Akhilrajtr

Reputation: 5182

Try this,

Assuming dataDict is a NSMutableDictionary and initialised.

- (void)addValueInDataDict:(id)value forKey:(NSString *)key {

     if ([dataDict objectForKey:key] != nil) {
         //Already exist a value for the key
         id object = [dataDict objectForKey:key];
         NSMutableArray *objectArray;
         if ([object isKindOfClass:[NSMutableArray class]]) {

             objectArray = (NSMutableArray *)object;
         } else {

            NSMutableArray *objectArray = [[NSMutableArray alloc] init];
         }
         [objectArray addObject:value];
         [dataDict setObject:objectArray forKey:key];
     } else {
         //No value for the key
         [dataDict setObject:value forKey:key];
     }
}

Upvotes: 2

Related Questions