2012-05-15 80 views
0

我想嘗試按NSMutableDictionary的值排序,其中的密鑰是price,其中NSMutableArray的人是。如何根據NSMutableDictonary的值對NSArray進行排序

這樣的...

people = [ 
    ["price" => 133, "name" => "banana"], 
    ["price" => 333,"name" => "apple"], 
    ["price" => 3, "name" => "orange"], 
] 

我想是這樣的:

copiedPeople = [ 
    ["price" => 3, "name" => "orange], 
    ["price" => 133,"name" => "banana"], 
    ["price" => 333, "name" => "apple"], 
] 

你有什麼想法?

回答

1

sortUsingComparator:讓你傳入一個說明如何對項目進行排序的塊。所以,你可以這樣做:

[people sortUsingComparator: ^NSComparisonResult(id obj1, id obj2) { 
    return [[obj1 objectForKey: @"price"] compare: [obj2 objectForKey: @"price"]]; 
}]; 

編輯:剛纔看到您的編輯...你可以使用sortedArrayUsingComparator:的NSArray上創建一個新的有序數組。

+0

謝謝!這個很酷! – nobinobiru

相關問題