How to add the object array to nsmutabledictionary with another array as key

Bala picture Bala · Nov 23, 2011 · Viewed 24k times · Source
for(Attribute* attribute in appDelegate.attributeArray) {
    attribute = [appDelegate.attributeArray objectAtIndex:z];
    attri = attribute.zName;
    int y = 0;
    for(Row* r in appDelegate.elementsArray) {
        r = [appDelegate.elementsArray objectAtIndex:y];
        NSString *ele = r.language;
        if([attri isEqualToString:ele]) {
            NSLog(@"=================+++++++++++++++++%@ %@",attri, r.user);
            [aaa insertObject:r atIndex:y]; //here i am adding the value to array
            [dict setObject:aaa forKey:attri]; //here i am adding the array to dictionary
        }
        y++;
    }
    z++;
    NSLog(@"============$$$$$$$$$$$$$$$$$$$$$$$++++++++++ %@",dict);
}

key in one array and the value in the another array and the value array is in object format.

I need to store the multi object for the single key. The attributeArray has the key value and the elementsArray has the object. For example the attributeArray might have the values

 " English, French, German..."

and the elementsArray might have the object value

"<Row: 0x4b29d40>, <Row: 0x4b497a0>, <Row: 0x4e38940>, <Row: 0x4b2a070>, <Row: 0x4b29ab0>, <Row: 0x4b178a0> "

In the first value I need to store the two object and for second key I need to store 3 objects and for the third key in need to store last two objects in the dictionary.

Answer

Denis picture Denis · Nov 23, 2011

For super-simplification you can use the following code:

NSArray *keys = ...;
NSArray *values = ...;

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: values forKeys: keys];

Hope, this helps.

UPDATE:

to store multiple values for single key in the dictionary, just use NSArray / NSMutableArray as your object:

NSArray *keys = ...;
NSMutableDictionary *dict = [NSMutableDictionary dictionary];

for( id theKey in keys) 
{
  NSMutableArray *item = [NSMutableArray array];
  [item addObject: ...];
  [item addObject: ...];
  ...

  [dict setObject: item forKey: theKey];
}

If you don't know all the values for the key from the beginning and need to add them one by one, you can use the following approach:

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

for( /*some cycling condition here */) 
{
  id keyToUse = ...;
  id valueToAdd = ...;

  id foundArray = [dict objectForKey: keyToUse];
  if ( nil == foundArray )
  {
    foundArray = [NSMutableArray array];
    [dict setObject: foundArray forKey: keyToUse];
  }

  [foundArray addObject: valueToAdd];
}