1

私は辞書の配列を持っています..このように見えます。

(
   {name = somename;
    date = NSDate;
    other_params = some other params;
   },
   ...
)

次に、配列アイテムをNSDateで並べ替えるにはどうすればよいですか(古いものから新しいものへ、またはその逆)。基本的な選択ソートアルゴリズムを実行するだけですか、それとももっと短い方法がありますか?

4

2 に答える 2

3

記述子またはコンパレータを使用して、より快適に感じるものなら何でも配列をソートできます。コンパレータの使用例を次に示します。

NSArray *sortedArray = [myArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
    return [[obj1 date] compare:[obj2 date]];
}];
于 2012-04-12T02:18:20.157 に答える
0

記述子の並べ替えオプションは次のとおりです。

// Adjust the 'ascending' option to invert the sort order.    
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
// The sort descriptors have to go into an array.
NSArray *sortDescriptors = [NSArray arrayWithObject:dateSortDescriptor];

NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

NSMutableArrayを使用していて、元の順序を維持する必要がない場合は、その場で並べ替えることもできます。

于 2012-04-12T02:32:49.633 に答える