[Objective-C] 配列に格納された数値データ、文字列、NSDictionary をソートする
配列(NSArray, NSMutableArray)に格納された数値データ、文字列、NSDictionary をソートする方法を紹介します。
配列のソートには、NSSortDescriptor を利用します。NSortDescriptor には、ソート順(昇順、降順)の指定、比較するキーを登録して使用します。実際のコードとその出力結果を載せておきますので、参考にしてみてください。
数値データ(NSNumber)
NSArray *array = @[@10, @1, @100, @0.1, @1000];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sortDescriptor]];
NSLog(@"%@", sortedArray);
// 出力結果
// (
// "0.1",
// 1,
// 10,
// 100,
// 1000
// )
文字列(NSString)
NSArray *array = @[@"The", @"Catcher", @"in", @"the", @"Rye"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sortDescriptor]];
NSLog(@"%@", sortedArray);
// 出力結果
// (
// Catcher,
// Rye,
// The,
// in,
// the
// )
辞書データ(NSDictionary)
NSArray *array = @[@{@"text" : @"The", @"value" : @10},
@{@"text" : @"Catcher", @"value" : @1},
@{@"text" : @"in", @"value" : @100},
@{@"text" : @"the", @"value" : @0.1},
@{@"text" : @"Rye", @"value" : @1000}];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"text" ascending:YES];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sortDescriptor]];
NSLog(@"%@", sortedArray);
// 出力結果
// (
// {
// text = Catcher;
// value = 1;
// },
// {
// text = Rye;
// value = 1000;
// },
// {
// text = The;
// value = 10;
// },
// {
// text = in;
// value = 100;
// },
// {
// text = the;
// value = "0.1";
// }
// )