配列のデータをソートする

配列内のデータをソートしたいと思ったので調べてみた

数値データ(NSNumber)の場合

 NSArray *numbers = @[@100, @10, @1000, @1, @10000];
   
 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
 NSArray *sortedArray = [numbers sortedArrayUsingDescriptors:@[sortDescriptor]];
出力結果
( 1, 10, 100, 1000, 10000 )

文字列(NSString)の場合

 NSArray *colors = @[@"Yellow", @"Red", @"White", @"Pink", @"Green"];
   
 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
 NSArray *sortedArray = [colors sortedArrayUsingDescriptors:@[sortDescriptor]];
出力結果
( Green, Pink, Red, White, Yellow )

辞書データ(NSDictionary)の場合

 NSArray *array = @[@{@"color" : @"Yellow", @"numbers" : @100},
                    @{@"color" : @"Red", @"numbers" : @10},
                    @{@"color" : @"White", @"numbers" : @1000},
                    @{@"color" : @"Pink", @"numbers" : @1},
                    @{@"color" : @"Green", @"numbers" : @10000}];
   
 NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"text" ascending:YES];
 NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sortDescriptor]];
出力結果
(
{
color = Yellow;
number = 100;
},
{
color = Red;
number = 10;
},
{
color = White;
number = 1000;
},
{
color = Pink;
number = 1;
},
{
color = Green;
number = 10000;
}
)
最終更新:2014年10月09日 11:07