sixstatesaway
sixstatesaway

Reputation: 1106

Sorting an NSDictionary based on the number of values be key

I have an NSDictionary that has a key that is a country and object that is an array of cities:

United States
    New York
    Portland
    Austin
    San Francisco

India
    New Delhi

Belgium
    Antwerp
    Brussels

I would like to create a dictionary from this dictionary that looks like:

United States
    4

Belgium 
    2

India 
    1

So sorted from highest number of keys to the lowest number of keys, and the new key is the number of keys in the original dictionary. Is this possible? What would be the most efficient way?

The farthest I've gotten is by using

NSComparator sorter = ^NSComparisonResult(id a, id b)
{
    NSArray* a1 = a;
    NSArray* a2 = b;
    if([a1 count] > [a2 count]) return NSOrderedAscending; 
    if([a1 count] < [a2 count]) return NSOrderedDescending; 
    return NSOrderedSame;
}

NSArray* ordered = [dictionary keysSortedByValueUsingComparator:sorter];

But then I only have an ordered array, not that values attached to that array.

Thanks in advance!

Upvotes: 0

Views: 736

Answers (3)

uchuugaka
uchuugaka

Reputation: 12782

You can't sort NSDictionary it's an unordered collection. You can build a representation. You've done the work already. You just need an array to represent it. The sorted array can hold your key paths to each key in the dictionary.

Upvotes: 0

soryngod
soryngod

Reputation: 1827

You can do it like this for key:

NSArray *sortKeys = [[dictionary allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortKeys) {
    [sortedValues addObject: [dictionary objectForKey: key]];
}

And for value:

 NSArray *sortedKeys = [dictionary keysSortedByValueUsingSelector: @selector(compare:)];

Upvotes: 1

Ander
Ander

Reputation: 3698

You need to create a new class that has countryName and a numberOfCities members. Once you've done this, you can create an array of these objects and sort them.

For example, the custom object could have a header file similar to this:

@interface Country : NSObject

@property (nonatomic, strong) NSString *countryName;
@property (nonatomic) NSUInteger numberOfCities;

@end

Upvotes: 1

Related Questions