user984248
user984248

Reputation: 149

Add to NSDictionary entries to NSMutableDictionary

I have a for loop that goes through a series of dictionaries in an array.

How can I consolidate all the dictionaries entries as it goes through the for loop into one NSMutableDictionary?

I tried addEntriesFromDictionary, but its not working. Thanks for your help.

for (int i=0; i<sections.count; i++){

    formElements    = [[sections objectAtIndex:i]objectForKey:@"Dictionary"];        
}

Upvotes: 11

Views: 15222

Answers (4)

Jonathan
Jonathan

Reputation: 3034

NSMutableDictionary * mutableDict = [NSMutableDictionary dictionary];

for (NSDictionary * formElements in sections)
{
    [mutableDict addEntriesFromDictionary:formElements];
}

This should work if It's correct that they don't share any keys.

Upvotes: 15

Pandey_Laxman
Pandey_Laxman

Reputation: 3918

NSMutableDictionary *mDict=[[NSMutableDictionary alloc]init];
    NSMutableDictionary *mDict2=[[NSMutableDictionary alloc]init];

//later suppose you have 5 object in mDict and 2 object in mDict2. combine in this Way.
    NSMutableArray *keys=[[NSMutableArray alloc]init];
    NSMutableArray *obj=[[NSMutableArray alloc]init];

    keys=[[mDict allKeys] mutableCopy];
    obj=[[mDict allValues] mutableCopy];

    [keys addObjectsFromArray:[mDict2 allKeys]];
    [obj addObjectsFromArray:[mDict2 allValues]];

    NSMutableDictionary *dict=[[NSMutableDictionary alloc]initWithObjects:obj forKeys:keys];

Upvotes: 1

Engeor
Engeor

Reputation: 328

You can enumerate your dictionaries with -objectEnumerator or other methodfs of NSDictionary.

So inside your loop you enumerate your dictionary and add all objects an keys into one big dictionary.

Upvotes: 0

Pandey_Laxman
Pandey_Laxman

Reputation: 3918

you can add dictionary object like below.

NSMutableDictionary *mDict=[NSMutableDictionary dictionary];
    [mDict addEntriesFromDictionary:DictObj];

Upvotes: 15

Related Questions