2013-11-14 77 views
0

的一個NSArray我的NSDictionary unsortedArray的一個NSArray樣子:排序的NSDictionary

( 
    {symbol = "ABC"; price = "9.01";} 
    {symbol = "XYZ"; price = "3.45";} 
    ... 
    (

這裏是排序代碼:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"price" ascending:YES]; 
    NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor]; 
    NSArray *sortArray = [unsortedArray sortedArrayUsingDescriptors:sortedDescriptors]; 

    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"symbol" ascending:YES]; 
    NSArray *sortDescriptors = [NSArray arrayWithObject:descriptor]; 
    NSArray *sortArray = [unsortedArray sortedArrayUsingDescriptors:sortedDescriptors]; 

的符號鍵排序結果是好的,但價格的關鍵沒有排序。什麼可能是錯的?價格是在NSString,但想排序它看起來像

3.45 
    9.01 
    ... 

在此先感謝。

+1

這似乎不是你的實際代碼:你使用變量名'sortedDescriptors',它在上面代碼中沒有定義。請發佈您的實際代碼。 – Monolo

+0

「什麼可能是錯的?」那麼,*做錯了什麼?畢竟,這兩種價格是正確分類的。 –

回答

2

在字典中使用NSNumber作爲價格,並且排序描述符將在數字值而不是字符串上工作。

NSArray *dictArray = @[ @{@"symbol" : @"ABC", @"price" : @9.01}, 
         @{@"symbol" : @"XYZ", @"price" : @3.45} ]; 

,或者,如果價格是一個字符串

NSArray *dictArray = @[ @{@"symbol" : @"ABC", @"price" : @"9.01"}, 
         @{@"symbol" : @"XYZ", @"price" : @"3.45"} ]; 

使用比較它要求的價格比較一對的字典,例如

NSArray *sortedArray = [dictArray 
         sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dict1, 
                     NSDictionary *dict2) { 

    double price1 = [[dict1 valueForKey:@"price"] doubleValue]; 
    double price2 = [[dict2 valueForKey:@"price"] doubleValue]; 

    if(price1 > price2) 
     return (NSComparisonResult)NSOrderedDescending; 

    if(price1 < price2) 
     return (NSComparisonResult)NSOrderedAscending; 

    return (NSComparisonResult)NSOrderedSame; 

}]; 
+0

謝謝。但unsortedArray已經存在。我需要對這個數組進行排序。 – user2543991

+0

我已經改變了我的答案,包括使用比較器進行排序,以正確排序數字作爲字符串 – SPA

+0

再次感謝。有用。 – user2543991