Objective Cの配列ソートをする方法3(sortedArrayUsingDescriptors:)

1.Carクラス 
Car.m
#import “Car.h"
@implementation Car
+(Car *)initWithName:(NSString *)name{
Car *car = [Car alloc] init];
car.name = name;
return car;
}
2.Personクラス 
Person.m
#import “Person.h"
#import “Car.h"
@implementation Person

+(Person *)personWithAge:(int)age withName:(NSString *)name withCar:(Car *)car{
Person *person = [[Person alloc] init];
person.age = age;
person.name = name;
person.car = car;
return person;
}
-(NSString *)description{
return [NSString stringWithFormat:@"age is %zi , name is %@, car is %@",_age,_name,_car.name];
}
主なメソッド:
void sortArray_startnews24(){
//carの種類
Car *car1 = [Car initWithName:@"豊田"];
Car *car2 = [Car initWithName:@"本田"];
Car *car3 = [Car initWithName:@"BMW"];

//Personオブジェクトにcar2、car1、car1、car3、car2を渡す
Person *p1 = [Person personWithAge:23 withName:@"春菜" withCar:car2];
Person *p2 = [Person personWithAge:21 withName:@"景子" withCar:car1];
Person *p3 = [Person personWithAge:24 withName:@"桃子" withCar:car1];
Person *p4 = [Person personWithAge:23 withName:@"美智子" withCar:car3];
Person *p5 = [Person personWithAge:23 withName:@"京子" withCar:car2];

//配列を追加
NSArray *array = [NSArray arrayWithObjects:p1,p2,p3,p4,p5, nil];

//ソート記述子を構築する
NSSortDescriptor *carNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"car.name" ascending:YES];
NSSortDescriptor *personNameDesc = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSSortDescriptor *personAgeDesc = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];

NSArray *descriptorArray = [NSArray arrayWithObjects:personAgeDesc,carNameDesc,personNameDesc, nil];

NSArray *sortedArray = [array sortedArrayUsingDescriptors: descriptorArray];
NSLog(@"%@",sortedArray);
}

IOS

Posted by arkgame