2013-06-04 244 views
0

我正在嘗試按升序對NSDictionary排序。我使用此代碼:按升序排列NSDictionary

NSDictionary *valDict = self.mGetDataDict[key][rowKey]; 

for (NSString *valueKey in 
    [[valDict allKeys] sortedArrayUsingSelector:@selector(compare:)]) 
{     
    if ([valueKey isEqualToString:@"attr"]) 
    { 
     dictRow = self.mGetDataDict[key][rowKey][valueKey]; 
    } 
    else { 
     NSString *valKey = self.mGetDataDict[key][rowKey][valueKey]; 
     [arrSeatsStatus addObject:valKey]; 
    } 
} 

這是我得到的輸出:

1 = off; 
10 = off; 
2 = on; 
3 = on; 
4 = on; 
5 = on; 
6 = on; 
7 = on; 
8 = on; 
9 = on; 

這是所需的輸出:

1: "off", 
2: "on", 
3: "on", 
4: "on", 
5: "on", 
6: "on", 
7: "on", 
8: "on", 
9: "on", 
10: "off" 

所需的輸出爲未來的實際值來自JSON。

回答

6

您可以使用NSSortDescriptor這樣的:

NSArray* array1 = @[@"1 = off", @"10 = off", @"2 = on", @"3 = on"]; 
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES selector:@selector(localizedStandardCompare:)]; 

NSLog(@"Ordered array: %@", [array1 sortedArrayUsingDescriptors:@[ descriptor ]]); 

產生這樣的輸出:

2013-06-04 12:26:22.039 EcoverdFira[3693:c07] Ordered array: (
    "1 = off", 
    "2 = on", 
    "3 = on", 
    "10 = off" 
) 

有上NSSortedDescriptorhere好文章。

+6

這是如何標記爲正確答案?這甚至不排序一個字典,它只是排序一個數組! – holierthanthou84

0

獲取值的數組,排序該數組,然後獲取與該值對應的鍵。

你可以用得到的值:

NSArray* values = [myDict allValues]; 
NSArray* sortedValues = [values sortedArrayUsingSelector:@selector(comparator)]; 

但是,如果集合是你在你的例子表明,(我的意思是,你可以推斷出從鍵的值),可以隨時排序鍵而不是搞亂值。

使用:

NSArray* sortedKeys = [myDict keysSortedByValueUsingSelector:@selector(comparator)]; 

比較器是被髮送到你要訂購的對象的消息選擇。

如果你想命令字符串,那麼你應該使用NSString比較器。 NSString比較器是:caseInsensitiveCompare或localizedCaseInsensitiveCompare :.

如果這些都不是有效的,你可以調用自己的比較功能

[values sortedArrayUsingFunction:comparatorFunction context:nil] 

被comparatorFunction(從AppleDocumentation

NSInteger intSort(id num1, id num2, void *context) 
{ 
    int v1 = [num1 intValue]; 
    int v2 = [num2 intValue]; 
    if (v1 < v2) 
     return NSOrderedAscending; 
    else if (v1 > v2) 
     return NSOrderedDescending; 
    else 
     return NSOrderedSame; 
} 
2

嘗試使用這個....

//變更.......

NSArray *valDict = [[self.mGetDataDict allValues] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 
NSMutableDictionary *orderedDictionary=[[NSMutableDictionary alloc] init]; 

for (NSString *valor in valDict) 
{ 
    for (NSString *clave in [yourDictionary allKeys]) 
    { 
     if ([valor isEqualToString:[valDict valueForKey:clave]]) 
     { 
      [orderedDictionary setValue:valor forKey:clave]; 
     } 
    } 
} 
+0

它給錯誤無法識別的選擇器在第一行發送實例。 –

+0

看到我編輯的答案... –

+0

這不是問題,但[字母allKeys]來,而不是價值觀。問題是,即使勇氣== clave控制不進去。 –