2017-11-18 258 views
0

我有3個對象的數組。這些對象屬於字典類型。每個字典都有不同的密鑰。我想按字母順序對這個數組進行排序。按字母順序對字典進行排序

我的數組結構如下

MyListArray:({Return=something;},{Departure=something;},{Both=something;}); 

我如何按字母順序排序呢?

+0

你要像輸出: - 'MyListArray:({=兩個東西;},{ 出發=東西;},{回報=東西;});'??? –

+0

是的。那是我的預期輸出 –

+0

[Objective-C:基於字典條目對NSDictionary的鍵進行排序]的可能重複(https://stackoverflow.com/questions/11554780/objective-c-sort-keys-of-nsdictionary-基於字典條目) –

回答

1

使用sortedArrayUsingComparator:並比較比較器中的鍵。關鍵是字典allKeys中的第一個關鍵字。

NSArray *sortedArray = [myListArray sortedArrayUsingComparator:^(NSDictionary* _Nonnull obj1, NSDictionary* _Nonnull obj2) { 
    if (obj1.count == 0) { 
     if (obj2.count == 0) 
      return NSOrderedSame; 
     else 
      return NSOrderedAscending; 
    } 
    if (obj2.count == 0) 
     return NSOrderedDescending; 
    NSString *key1 = obj1.allKeys[0]; 
    NSString *key2 = obj2.allKeys[0]; 
    return [key1 compare:key2]; 
}];