【サンプルコードあり】NSArrayをNSDictionaryの特定キーの値でソート

iPhone

NSDictionaryを含むNSArrayを、NSDictionaryの特定のキーでソートしたい時があるかと思います。

例えば、NSDctionaryの数値が値になる「English」というキーで配列をソートしてみます。
誰が英語の点数が良かったかを出力しようかと思います。

まず、教科ごとの点数と名前を持つNSDictionaryの配列を用意

    NSDictionary* yamachan = [[NSDictionary alloc] initWithObjects: @[@"山ちゃん", @"80", @"30"] 
                                                                                          forKeys: @[@"Name", @"English", @"Mathmatics"]];
    NSDictionary* okamato = [[NSDictionary alloc] initWithObjects: @[@"岡本", @"67", @"60"] 
                                                                                        forKeys: @[@"Name", @"English", @"Mathmatics"]];
    NSDictionary* yamane = [[NSDictionary alloc] initWithObjects: @[@"山根", @"40", @"20"] 
                                                                                      forKeys: @[@"Name", @"English", @"Mathmatics"]];
    NSArray* students = @[yamachan, okamato, yamane];

次にこの配列を英語の点数順にソートします。

    NSArray* sorted_students = [students sortedArrayUsingFunction:compareFloat context:NULL];

ソートするには、「sortedArrayUsingFunction: context:」がキモ。
第1引数は、比較を行うためのC言語の関数を定義
第2引数は、第1引数で指定した関数の引数を定義

比較を行う関数は以下です。

 NSComparisonResult compareFloat(id value1, id value2, void *context)
 {
    float floatValue1 = [(NSNumber*)[value1 valueForKey: @"English"] floatValue];
    float floatValue2 = [(NSNumber*)[value2 valueForKey: @"English"] floatValue];
    
    if(floatValue1 > floatValue2){
        return NSOrderedDescending;
    }else if(floatValue1 < floatValue2){
        return NSOrderedAscending;
    }else{
        return NSOrderedSame;
    }
 }

あとは配列を出力するだけ。

    NSDictionary* top = [sorted_students objectAtIndex: 0];
    NSLog(@"一番英語の点数が良かったのは、%@です。", [top valueForKey:@"Name"]);

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です