简体   繁体   中英

Creating NSDictionary with keys that have multiple values

I have a mutable array that contains NSDictionary dic1 objects,

each dictionary has a key called contactId , more than one dictionary can have the same value for contactId .

What I want to do is to create an NSDictionary with unique contactIds as the keys and an array value that contains a list of all NSDictionary dic1 objects that have the value contactId equal to the key.

How can I do this?

My data looks like this:

**myArray**:[  **dic1** {contactId = x1 , name = name1 }, **dic2**{contactId = x2, name = 
name2 }, **dic3**{contactId = x1, name = name3} ]

I want it to become like this:

**NSDictionary**: { **x1**:[dic1, dic3], **x2**:[dic2] } 

Use fast enumeration:

NSMutableDictionary *result = [NSMutableDictionary dictionary];

for (id obj in myArray)
{
    NSString *contactId = [obj objectForKey:@"contactId"];
    NSMutableSet *contacts = [result objectForKey:contactId];
    if (!contacts)
    {
        contacts = [NSMutableSet set]
        [result setObject:contacts forKey:contactId];
    }
    [contacts addObject:obj];
}

You could use blocks for no real added benefit:

__block NSMutableDictionary *result = [NSMutableDictionary dictionary];

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
    NSString *contactId = [obj objectForKey:@"contactId"];
    NSMutableSet *contacts = [result objectForKey:contactId];
    if (!contacts)
    {
        contacts = [NSMutableSet set]
        [result setObject:contacts forKey:contactId];
    }
    [contacts addObject:obj];
}];

How about the classic way?

NSMutableDictionary* Result;
NSEnumerator* Enumerator;
NSDictionary* Dict;
Result=[[NSMutableDictionary alloc] init];
Enumerator=[YourArray objectEnumerator];
while ((Dict=[Enumerator nextObject])!=nil)
{
   NSString* ContactID;
   NSMutableSet* Contacts;
   ContactID=[Dict objectForKey:@"contactID"];
   Contacts=[Result objectForKey:ContactID];
   if (Contacts==nil)
   {
      Contacts=[[NSMutableSet alloc] init];
      [Result setObject:Contacts forKey:ContactID];
      [Contacts release];
   }
   [Contacts addObject:Dict];
}

This should create a Result dictionary. I haven't tested (or even compiled) this, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM