2013-07-16 62 views
0

我有了一個密鑰是一個國家和對象,它是城市的一個數組一個NSDictionary:排序一個NSDictionary基於值的數量是關鍵

United States 
    New York 
    Portland 
    Austin 
    San Francisco 

India 
    New Delhi 

Belgium 
    Antwerp 
    Brussels 

我想創建從字典這本字典,看起來像:

United States 
    4 

Belgium 
    2 

India 
    1 

所以從按鍵到最低的數字鍵,而新的鍵的最高數量排序是在原詞典按鍵的數量。這可能嗎?什麼是最有效的方法?

我已經得到最遠的是通過使用

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]; 

但後來我只有一個有序的陣列,而不是連接到該數組值。

在此先感謝!

+0

可能這將有助於 http://stackoverflow.com/questions/9708742/getting-nsdictionary-keys-sorted-by-their-respective-values – 2013-07-16 07:43:01

+1

需要注意的是一本字典是無序的關鍵的集合/值對。您無法規定字典中的密鑰順序。 –

回答

1

您需要創建一個具有countryNamenumberOfCities成員的新類。完成此操作後,可以創建這些對象的數組並對它們進行排序。

例如,自定義對象可以有一個類似的頭文件:

@interface Country : NSObject 

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

@end 
0

你可以做這樣的關鍵:

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

而對於價值:

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

你不能排序NSDictionary它是一個無序的集合。 您可以構建一個表示。 你已經完成了這項工作。你只需要一個數組來表示它。 排序後的數組可以保存到字典中每個鍵的鍵路徑。