简体   繁体   中英

How to get unique keys in a NSDictionary?

This is the NSDictionary I have:

locations: {
    509f3a914d026b589ba3a090 =     {
        coordinates =         {
            latitude = "29.76429";
            longitude = "-95.3837";
        };
        country = USA;
        id = 509f3a914d026b589ba3a090;
        name = Houston;
        state = Texas;
    };
    509f3b3a4d026b589ba3a091 =     {
        coordinates =         {
            latitude = "3.138722";
            longitude = "101.686849";
        };
        country = Malaysia;
        id = 509f3b3a4d026b589ba3a091;
        name = "Kuala Lumpur";
    };
    509f475b4d026b589ba3a093 =     {
        coordinates =         {
            latitude = "32.803468";
            longitude = "-96.769879";
        };
        country = USA;
        id = 509f475b4d026b589ba3a093;
        name = Dallas;
        state = Texas;
    };
}

What I am wanting to do is to just get the countries and as you can tell I have two values for "USA". I just want to extrapolate USA and Malaysia. And not USA,Malaysia, USA.

I hope I am making sense

I think the simplest method would be:

[NSSet setWithArray:[[dictionary allValues] valueForKey:@"country"]];

So you:

  1. get the array of all values in the top-level dictionary;
  2. call valueForKey: on that array — which is defined to call valueForKey: on everything in the array in turn and then return an array of the answers, and valueForKey: on a dictionary is the same as objectForKey: if the key in question doesn't being with an '@';
  3. create a set from the resulting array, hence resolving any repetitions.

You could add a call to allObjects on the resulting set if you wanted to end up with an array.

Say you have a dictionary called locations and one of the objects in your dictionary is a country. Also you say just extrapolate I'll assume you want to add it to some array or something. For this problem you could use a set to make sure you aren't entering the same country more then once.

NSMutableSet *set = [NSMutableSet set];
NSMutableArray *array = [NSMutableArray array];

NSString *country = [locations objectForKey:@"country"]; 
if ([set containsObject:country])
{
    [array addObject:country]; // Extrapolating country from dictionary to array
    [set addObject:country]; // Addind it to set to check later
}

I would do this way:

NSMutableArray *newArray = [NSMutableArray array];
NSMutableSet *currentCountries = [NSMutableSet set];
for(NSDictionary* dic in [[currentDict objectForKey:@"locations"] allValues])
{
    if(![currentCountries containsObject:[dic objectForKey:@"country"])
    {
        [currentCountries addObject:[dic objectForKey:@"country"]]
        [newArray addObject:dic];
    }
}

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