NSArray/NSMutableArray をソートする | 静岡県富士市在住のiPhoneアプリ開発者ブログ

NSArray/NSMutableArray をソートする

NSArray に格納した任意のオブジェクトの配列を何らかのキーでソートするには

- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context

を使う

第1引数は、比較を行うためのC言語の関数を定義する
第2引数は、第1引数で指定した関数の引数を定義できる

例えば、下の関数では、Info というクラスの percent という実数をキーとして降順にソートする

NSInteger compareInfo(id aInfo1, id aInfo2, void *context)
{
float dpercent1 = ((Info*) aInfo1).percent;
float dpercent2 = ((Info*) aInfo2).percent;

if (dpercent1 < dpercent2)
return NSOrderedDescending;
else if (dpercent1 > dpercent2)
return NSOrderedAscending;
else
return NSOrderedSame;
}



で、

NSArray *array = [infos sortedArrayUsingFunction: compareInfo context:NULL];
//infos は、Infoクラスのインスタンスの配列

こうすると、array には、infos を percent で降順ソートした配列が格納される