2013-08-07 85 views
0

基於NSMutableDictionary s的NSMutableArray s,我嘗試基於按升序排列的鍵進行排序。該密鑰被稱爲Product Sale Price,它從服務器返回,如$350這樣的字符串。所以我字符串的第一個字符來比較int類型:sortedArrayUsingFunction沒有正確排序

//Sorting function 
NSInteger priceComparator(NSMutableDictionary *obj1, NSMutableDictionary *obj2, void *context){ 
    int v1 = [[[obj1 valueForKey:@"Product Sale Price"]substringFromIndex:1] intValue]; 
    int v2 = [[[obj2 valueForKey:@"Product Sale Price"]substringFromIndex:1] intValue]; 
    NSLog(@"v1, v2: %i | %i",v1,v2); 
    if (v1 > v2){ 

     NSLog(@"v2 is smaller: <%i>",v2); 
     return v2; 
    } 
    else if (v1 < v2){ 

     NSLog(@"v1 is smaller: <%i>",v1); 
     return v1; 
    } 
    else 
     return NSOrderedSame; 
} 


//Somewhere in the code 
arrayProduct = (NSMutableArray*)[arrayProduct sortedArrayUsingFunction:priceComparator context:nil]; 
NSLog(@"%@",arrayProduct);//The array is not sorted as expected, still random order 

所以基本上,順序是不以某種方式影響,雖然我調試步驟b一步,所有的比較都是正確的。我錯過了什麼嗎?

編輯:

這裏是arrayProduct一些項目:

(
    { 
     "Product ID" = 15119; 
     "Product Sale Price" = "$395"; 
    }, 

    { 
     "Product ID" = 16897; 
     "Product Sale Price" = "$75"; 
    } 
) 

回答

3

您需要返回NSOrderedAscendingNSOrderedDescending代替v1v2。如果排序以相反的順序結束 - 交換您返回的兩個中的哪一個。

0

你可以使用排序描述符來排序數組,如下面的代碼這裏key是你想要對數組進行排序的參數的關鍵字。 例如,您想按名稱排序,則鍵爲「名稱」

NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"key" ascending:YES] autorelease]; 
NSArray *sortDescriptors = [[NSArray alloc]init]; 
sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; 
NSArray *sortedArray; 
sortedArray = [Array sortedArrayUsingDescriptors:sortDescriptors];